Class: Mbeditor::EditorsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/mbeditor/editors_controller.rb

Constant Summary collapse

IMAGE_EXTENSIONS =
%w[png jpg jpeg gif svg ico webp bmp avif].freeze
RUBY_DEFS_WARM_MUTEX =
Mutex.new
TOTAL_LINES_CACHE_MAX =
50
TOTAL_LINES_MUTEX =
Mutex.new
GIT_STATUS_TTL =
3
GIT_STATUS_MUTEX =
Mutex.new
IMPORT_MAX_FILES =

Kept below Rack's multipart_part_limit (128 file parts in Rack 3.2), which is enforced during param parsing — outside the action, where this controller's rescue cannot turn it into a clean 422. A batch larger than the Rack limit raises MultipartPartLimitError and surfaces as a 500, so this guard is only reachable if it trips first.

100
IMPORT_MAX_TOTAL_BYTES =
50 * 1024 * 1024
STATE_MAX_BYTES =
EditorStateService::STATE_MAX_BYTES
HISTORY_MAX_OPS =
10_000
HISTORY_COMPACT_TARGET =
5_000
RUBY_LSP_METHODS =

The whitelist is the trust boundary: only these reach the language server. Symbol values are handled locally instead of being forwarded; they need no path, no document and no running process.

The first four have bespoke translators producing 1-based, editor-shaped payloads, kept for their existing consumers. Everything added since is in RUBY_LSP_RAW below: raw LSP JSON, 0-based, through one URI sanitizer. Eight more hand-written translators would be ~200 lines restating shapes Monaco already understands.

{
  "definition"       => "textDocument/definition",
  "hover"            => "textDocument/hover",
  "completion"       => "textDocument/completion",
  "diagnostics"      => "textDocument/diagnostic",
  "references"       => "textDocument/references",
  "document_highlight" => "textDocument/documentHighlight",
  "document_symbol"  => "textDocument/documentSymbol",
  "folding_range"    => "textDocument/foldingRange",
  "formatting"       => "textDocument/formatting",
  "signature_help"   => "textDocument/signatureHelp",
  "selection_range"  => "textDocument/selectionRange",
  "prepare_rename"   => "textDocument/prepareRename",
  "health"           => :health,
  "restart"          => :restart
}.freeze
RUBY_LSP_RAW =

Passed through as raw LSP JSON rather than translated. Ranges stay 0-based on the wire and are converted by one helper at the Monaco provider.

%w[
  references document_highlight document_symbol folding_range
  formatting signature_help selection_range prepare_rename
].freeze
RUBY_LSP_POSITIONLESS =

Whole-document requests, which carry no cursor position.

%w[
  textDocument/diagnostic textDocument/documentSymbol textDocument/foldingRange
  textDocument/formatting
].freeze
RUBY_LSP_EXTRA_PARAMS =

Extra params per method, merged into the request alongside the position. Values may be a hash or a callable taking the params hash.

{
  "textDocument/references" => { context: { includeDeclaration: true } },
  # selectionRange takes a list of positions, not the single `position` the
  # positional branch supplies, so it builds its own from the same params.
  "textDocument/selectionRange" => lambda { |p|
    { positions: [{ line: [p[:line].to_i - 1, 0].max,
                    character: [p[:character].to_i - 1, 0].max }] }
  },
  "textDocument/formatting" => lambda { |p|
    { options: { tabSize: (p[:tab_size].presence || 2).to_i,
                 insertSpaces: p[:insert_spaces].to_s != "false" } }
  }
}.freeze
RUBY_LSP_DIAGNOSTICS_TIMEOUT =

RuboCop's first run inside a freshly booted ruby-lsp is far slower than a hover/definition lookup, so the requests that go through RuboCop — diagnostics and formatting — get their own budget.

10
RUBY_LSP_RUBOCOP_METHODS =
%w[textDocument/diagnostic textDocument/formatting].freeze
RUBY_CONSTANT_PATH =

ruby-lsp renames constants only (Rename#perform locates ConstantReadNode | ConstantPathNode | ConstantPathTargetNode and nothing else), so anything that isn't a constant path is rejected before we ask.

/\A[A-Z][A-Za-z0-9_]*(::[A-Z][A-Za-z0-9_]*)*\z/
RUBY_LSP_RENAME_TIMEOUT =

Rename#collect_text_edits globs **/*.rb and Prism-parses every hit, which is seconds on a large app rather than the usual milliseconds.

30

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cached_git_status(root) ⇒ Object

git_status is polled every 5s by every open tab and costs two git subprocesses. A 3s TTL collapses the duplicates while staying inside one poll interval; any mutation drops it outright (broadcast_files_changed).



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'app/controllers/mbeditor/editors_controller.rb', line 55

def cached_git_status(root)
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  GIT_STATUS_MUTEX.synchronize do
    entry = (@git_status_cache ||= {})[root]
    return entry[:value] if entry && (now - entry[:ts]) < GIT_STATUS_TTL
  end

  value = yield
  GIT_STATUS_MUTEX.synchronize do
    (@git_status_cache ||= {})[root] = { ts: now, value: value }
  end
  value
end

.cached_total_lines(path, mtime) ⇒ Object

Small (path, mtime) => total-line-count cache so windowed reads of big files don't re-read the whole file just to report total_lines.



36
37
38
39
40
41
# File 'app/controllers/mbeditor/editors_controller.rb', line 36

def cached_total_lines(path, mtime)
  TOTAL_LINES_MUTEX.synchronize do
    entry = (@total_lines_cache ||= {})[path]
    entry && entry[:mtime] == mtime ? entry[:total] : nil
  end
end

.invalidate_git_status(root) ⇒ Object



69
70
71
72
# File 'app/controllers/mbeditor/editors_controller.rb', line 69

def invalidate_git_status(root)
  GIT_STATUS_MUTEX.synchronize { (@git_status_cache ||= {}).delete(root) }
  nil
end

.store_total_lines(path, mtime, total) ⇒ Object



43
44
45
46
47
48
49
50
# File 'app/controllers/mbeditor/editors_controller.rb', line 43

def store_total_lines(path, mtime, total)
  TOTAL_LINES_MUTEX.synchronize do
    cache = (@total_lines_cache ||= {})
    cache.delete(path)
    cache[path] = { mtime: mtime, total: total }
    cache.delete(cache.keys.first) while cache.length > TOTAL_LINES_CACHE_MAX
  end
end

Instance Method Details

#branch_stateObject

GET /mbeditor/branch_state?branch=... — load per-branch pane state



156
157
158
159
160
161
162
163
# File 'app/controllers/mbeditor/editors_controller.rb', line 156

def branch_state
  branch = sanitize_branch_name(params[:branch])
  return render json: {}, status: :bad_request unless branch

  render json: editor_state_service.read_branch_state(branch)
rescue StandardError
  render json: {}
end

#changelogObject

GET /mbeditor/changelog — serves the gem's CHANGELOG.md for the in-editor changelog tab.



1213
1214
1215
1216
1217
# File 'app/controllers/mbeditor/editors_controller.rb', line 1213

def changelog
  path = Mbeditor::Engine.root.join("CHANGELOG.md")
  content = path.exist? ? path.read(encoding: "utf-8") : ""
  render json: { content: content, version: Mbeditor::VERSION }
end

#clear_exceptionsObject

DELETE /mbeditor/exceptions — clear the recorded exceptions.



781
782
783
784
# File 'app/controllers/mbeditor/editors_controller.rb', line 781

def clear_exceptions
  ExceptionLog.clear!
  render json: { ok: true }
end

#client_configObject

GET /mbeditor/client_config — returns client-side configuration values



1182
1183
1184
1185
1186
1187
# File 'app/controllers/mbeditor/editors_controller.rb', line 1182

def client_config
  render json: {
    related_files_custom_paths: Array(Mbeditor.configuration.related_files_custom_paths),
    user_name: resolved_user_name
  }
end

#create_dirObject

POST /mbeditor/create_dir — create directory recursively



408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'app/controllers/mbeditor/editors_controller.rb', line 408

def create_dir
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path
  return render json: { error: "Cannot create directory in this path" }, status: :forbidden if path_blocked_for_operations?(path)

  result = FileOperationService.new(workspace_root).create_dir(path)
  broadcast_files_changed
  render json: result
rescue FileOperationService::FileExistsError
  render json: { error: "Path already exists" }, status: :unprocessable_content
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#create_fileObject

POST /mbeditor/create_file — create file and parent directories if needed



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'app/controllers/mbeditor/editors_controller.rb', line 391

def create_file
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path
  return render json: { error: "Cannot create file in this path" }, status: :forbidden if path_blocked_for_operations?(path)

  result = FileOperationService.new(workspace_root).create_file(path, params[:code].to_s)
  broadcast_files_changed([path])
  render json: result
rescue FileOperationService::FileExistsError
  render json: { error: "File already exists" }, status: :unprocessable_content
rescue FileOperationService::FileTooLargeError
  render_file_too_large(params[:code].to_s.bytesize)
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#definitionObject

GET /mbeditor/definition?symbol=...&language=... Looks up method definitions in workspace source files (Ripper) and in the Ruby/gem documentation via ri. Workspace results appear first.



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'app/controllers/mbeditor/editors_controller.rb', line 492

def definition
  symbol = params[:symbol].to_s.strip
  language = params[:language].to_s.strip

  return render json: { results: [] } if symbol.blank?
  return render json: { error: "Invalid symbol" }, status: :bad_request unless symbol.match?(/\A[a-zA-Z_]\w{0,59}[!?]?\z/)

  results = case language
            when "ruby"
              excl_patterns = Array(Mbeditor.configuration.excluded_paths).map(&:to_s).reject(&:blank?)
              workspace = RubyDefinitionService.call(
                workspace_root,
                symbol,
                excluded_paths: excl_patterns,
                included_dirs:  ruby_def_include_dirs
              )
              ri = RiDefinitionService.call(symbol)
              workspace + ri
            else
              []
            end

  render json: { results: results }
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#destroy_pathObject

DELETE /mbeditor/delete — remove file or directory



477
478
479
480
481
482
483
484
485
486
487
# File 'app/controllers/mbeditor/editors_controller.rb', line 477

def destroy_path
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path
  return render json: { error: "Cannot delete this path" }, status: :forbidden if File.exist?(path) && path_blocked_for_operations?(path)

  result = FileOperationService.new(workspace_root).destroy_path(path)
  broadcast_files_changed([path]) if result.key?(:type)
  render json: result
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#exceptionsObject

GET /mbeditor/exceptions — recorded host-app exceptions, newest first.

The cable push is the live path; this seeds the panel on load and covers hosts where ActionCable isn't available.



775
776
777
778
# File 'app/controllers/mbeditor/editors_controller.rb', line 775

def exceptions
  render json: { exceptions: ExceptionLog.entries,
                 enabled: Mbeditor.configuration.exception_capture != false }
end

#file_historyObject

GET /mbeditor/file_history?branch=X&path=Y



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'app/controllers/mbeditor/editors_controller.rb', line 206

def file_history
  branch = sanitize_branch_name(params[:branch])
  return render json: {}, status: :bad_request unless branch

  path = resolve_path(params[:path])
  return render json: {}, status: :forbidden unless path

  rel  = relative_path(path)
  hist = history_file_path(branch, rel)
  return render json: {} unless File.exist?(hist)

  data = JSON.parse(File.read(hist))

  if data['t']
    age = Time.now.utc - Time.parse(data['t'])
    if age > 7 * 24 * 3600
      FileUtils.rm_f(hist)
      return render json: {}
    end
  end

  render json: { base: data['base'], ops: data['ops'] || [] }
rescue JSON::ParserError
  FileUtils.rm_f(hist) rescue nil
  render json: {}
rescue StandardError
  render json: {}
end

#file_includesObject

GET /mbeditor/file_includes?path=app/models/article.rb Returns included/extended/prepended module names and their methods.



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# File 'app/controllers/mbeditor/editors_controller.rb', line 812

def file_includes
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path

  excl_patterns = Array(Mbeditor.configuration.excluded_paths).map(&:to_s).reject(&:blank?)
  module_names = RubyDefinitionService.includes_in_file(path)
  includes = module_names.filter_map do |mod_name|
    mod_file = RubyDefinitionService.module_defined_in(
      workspace_root, mod_name,
      excluded_paths: excl_patterns,
      included_dirs:  ruby_def_include_dirs
    )
    next unless mod_file

    defs    = RubyDefinitionService.defs_in_file(mod_file)
    methods = defs.flat_map do |method_name, entries|
      entries.map { |e| { name: method_name, line: e[:line], signature: e[:signature] } }
    end
    { name: mod_name, file: relative_path(mod_file), methods: methods }
  end
  render json: { includes: includes }
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#filesObject

GET /mbeditor/files — recursive file tree refresh=1 means "my view of the workspace is stale, drop your caches" — the client sends it after an external git checkout, which rewrites the tree without going through any mutation endpoint, so nothing here knows to invalidate. Without it the 15s tree TTL kept serving the old branch's file list, and the search cache the old branch's hits.



121
122
123
124
125
126
127
128
# File 'app/controllers/mbeditor/editors_controller.rb', line 121

def files
  if params[:refresh].present?
    FileTreeService.invalidate(workspace_root.to_s)
    SearchReplaceService.invalidate_cache(workspace_root.to_s)
  end
  tree = FileTreeService.cached_json(workspace_root)
  render json: tree[:body] if stale?(etag: tree[:digest], public: false)
end

#format_fileObject

POST /mbeditor/format — rubocop -A on buffer content; returns corrected content WITHOUT saving to disk

Accepts the current buffer content as code and formats it using a workspace-local tempfile so that RuboCop's config discovery walks up from the source file's own directory (finds the host app's .rubocop.yml). Does NOT write the result back to the original file — the frontend marks the tab dirty and lets the user decide when to save.



1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
# File 'app/controllers/mbeditor/editors_controller.rb', line 1247

def format_file
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path

  code = params[:code].to_s
  return render json: { error: "code required" }, status: :unprocessable_content if code.empty?

  ext = File.extname(File.basename(path))
  Tempfile.create([".mbeditor_fmt_", ext], File.dirname(path)) do |f|
    f.write(code)
    f.flush
    tmpfile = f.path

    cmd = AvailabilityProbe.rubocop_command(workspace_root) + [AvailabilityProbe.rubocop_server_flag(workspace_root), "-A", "--no-color", tmpfile]
    env = { 'RUBOCOP_CACHE_ROOT' => File.join(Dir.tmpdir, 'rubocop') }
    status = run_lint_command(env, cmd)[:exit_status]
    unless status.success? || status.exitstatus == 1
      return render json: { ok: false, content: code }
    end

    corrected = File.read(tmpfile, encoding: "UTF-8", invalid: :replace, undef: :replace)
    render json: { ok: true, content: corrected }
  end
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#git_infoObject

GET /mbeditor/git_info



917
918
919
# File 'app/controllers/mbeditor/editors_controller.rb', line 917

def git_info
  render json: GitInfoService.call(workspace_root.to_s)
end

#git_statusObject

GET /mbeditor/git_status



903
904
905
906
907
908
909
910
911
912
913
914
# File 'app/controllers/mbeditor/editors_controller.rb', line 903

def git_status
  root = workspace_root.to_s
  payload = self.class.cached_git_status(root) do
    output, status = GitService.run_git(root, "status", "--porcelain")
    { ok: status.success?,
      files: GitService.parse_porcelain_status(output),
      branch: GitService.current_branch(root) || "" }
  end
  render json: payload
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#importObject

POST /mbeditor/import — write files dragged in from outside the browser.

Multipart: files carries the bodies, paths the parallel list of workspace-relative targets, on_conflict one of ask/overwrite/rename. A structurally invalid batch is a 422; per-entry problems come back in the :errors array so one bad path never sinks the whole drop.



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'app/controllers/mbeditor/editors_controller.rb', line 428

def import
  files = Array(params[:files])
  paths = Array(params[:paths]).map(&:to_s)
  mode  = params[:on_conflict].presence || "ask"

  error = import_batch_error(files, paths, mode)
  return render json: { error: error }, status: :unprocessable_content if error

  entries = []
  errors  = []
  files.each_with_index do |file, i|
    full = resolve_path(paths[i])
    if full.nil? || path_blocked_for_operations?(full)
      errors << { path: paths[i], error: "Cannot write to this path" }
    else
      entries << { target_path: full, io: file }
    end
  end

  result = FileImportService.new(workspace_root).import(entries, on_conflict: mode.to_sym)
  result[:errors] = errors + result[:errors]

  written = result[:imported].map { |e| File.join(workspace_root.to_s, e[:path]) }
  broadcast_files_changed(written) if written.any?

  render json: result
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#indexObject

GET /mbeditor — renders the IDE shell



76
77
78
# File 'app/controllers/mbeditor/editors_controller.rb', line 76

def index
  render layout: "mbeditor/application"
end

#js_definitionObject

GET /mbeditor/js_definition?symbol=ReactWindow Searches workspace JS/JSX/TS/TSX files for global definitions of the named symbol.



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'app/controllers/mbeditor/editors_controller.rb', line 521

def js_definition
  symbol = params[:symbol].to_s.strip
  return render json: { results: [] } if symbol.blank?
  return render json: { error: "Invalid symbol" }, status: :bad_request \
    unless symbol.match?(/\A[a-zA-Z_$][a-zA-Z0-9_$]{0,59}\z/)

  parent = params[:parent].to_s.strip
  if parent.present?
    return render json: { error: "Invalid parent" }, status: :bad_request \
      unless parent.match?(/\A[a-zA-Z_$][a-zA-Z0-9_$]{0,59}\z/)
  else
    parent = nil
  end

  results = JsDefinitionService.new(symbol, workspace_root, parent: parent).call
  render json: { results: results }
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#js_globalsObject

GET /mbeditor/js_globals All top-level JS declarations across the workspace (the Sprockets global scope), plus config.js_global_identifiers. The editor declares these as ambient globals so cross-file component references don't produce "Cannot find name" diagnostics.



560
561
562
563
564
# File 'app/controllers/mbeditor/editors_controller.rb', line 560

def js_globals
  render json: JsGlobalsService.call(workspace_root)
rescue StandardError => e
  render json: { ok: false, error: e.message }, status: :unprocessable_content
end

#js_membersObject

GET /mbeditor/js_members?symbol=ReactWindow Searches workspace JS/JSX/TS/TSX files for properties/methods of the named global.



543
544
545
546
547
548
549
550
551
552
553
# File 'app/controllers/mbeditor/editors_controller.rb', line 543

def js_members
  symbol = params[:symbol].to_s.strip
  return render json: { members: [] } if symbol.blank?
  return render json: { error: "Invalid symbol" }, status: :bad_request \
    unless symbol.match?(/\A[a-zA-Z_$][a-zA-Z0-9_$]{0,59}\z/)

  members = JsMembersService.new(symbol, workspace_root).call
  render json: { symbol: symbol, members: members }
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#js_programObject

GET /mbeditor/js_program The workspace's own JS source, for Monaco's TypeScript program. With ?path= it returns just that one file, which is how the editor refreshes after a change without re-sending the whole tree.



570
571
572
573
574
575
576
577
578
579
# File 'app/controllers/mbeditor/editors_controller.rb', line 570

def js_program
  if params[:path].present?
    entry = JsProgramService.file(workspace_root, params[:path])
    return render json: { ok: true, file: entry }
  end

  render json: JsProgramService.call(workspace_root)
rescue StandardError => e
  render json: { ok: false, error: e.message }, status: :unprocessable_content
end

#lintObject

POST /mbeditor/lint — run rubocop --stdin (or haml-lint for .haml files)



972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
# File 'app/controllers/mbeditor/editors_controller.rb', line 972

def lint
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path

  filename = path.to_s
  code = params[:code] || File.read(path)

  if params[:language] == "javascript"
    unless JsSyntaxCheckService.available?
      return render json: { error: "JS syntax check not available", markers: [] }, status: :unprocessable_content
    end

    err = JsSyntaxCheckService.check(code)
    markers = if err
      line = err["line"] || 1
      col  = (err["column"] || 0) + 1
      [{
        severity: "error",
        copName: "Babel",
        correctable: false,
        message: "[babel] #{err['message']}",
        startLine: line, startCol: col, endLine: line, endCol: col + 1
      }]
    else
      # Only when the file parses: the scope lint would re-hit the same
      # parse error and report nothing useful on top of the marker above.
      JsSyntaxCheckService.scope_lint(workspace_root, code).map do |w|
        line = w["line"] || 1
        col  = (w["column"] || 0) + 1
        {
          severity: "warning",
          copName: "BabelScope",
          correctable: false,
          message: "[babel] #{w['message']}",
          startLine: line, startCol: col,
          endLine: line, endCol: col + [w["name"].to_s.length, 1].max
        }
      end
    end
    return render json: { markers: markers }
  end

  if File.basename(filename).end_with?('.haml')
    unless AvailabilityProbe.haml_lint(workspace_root)
      return render json: { error: "haml-lint not available", markers: [] }, status: :unprocessable_content
    end

    markers = run_haml_lint(code)
    return render json: { markers: markers }
  end

  cmd = AvailabilityProbe.rubocop_command(workspace_root) + [AvailabilityProbe.rubocop_server_flag(workspace_root), "--stdin", filename, "--format", "json", "--no-color"]
  env = { 'RUBOCOP_CACHE_ROOT' => File.join(Dir.tmpdir, 'rubocop') }
  output = run_with_timeout(env, cmd, stdin_data: code)

  idx = output.index("{")
  result = idx ? JSON.parse(output[idx..]) : {}
  result = {} unless result.is_a?(Hash)
  offenses = result.dig("files", 0, "offenses") || []

  markers = offenses.map do |offense|
    {
      severity: cop_severity(offense["severity"]),
      copName: offense["cop_name"],
      correctable: offense["correctable"] == true,
      message: "[#{offense['cop_name']}] #{offense['message']}",
      startLine: offense.dig("location", "start_line") || offense.dig("location", "line"),
      startCol: offense.dig("location", "start_column") || offense.dig("location", "column") || 1,
      endLine: offense.dig("location", "last_line") || offense.dig("location", "line"),
      endCol: offense.dig("location", "last_column") || offense.dig("location", "column") || 1,
      # Same predicate the ruby-lsp path uses, so dead code fades whichever
      # linter produced the offense. Plain rubocop JSON carries no
      # code_description, so there's no codeHref to pass on here.
      unnecessary: LspDiagnosticsTranslator.unnecessary?(offense["cop_name"])
    }
  end

  render json: { markers: markers, summary: result["summary"] }
rescue StandardError => e
  render json: { error: e.message, markers: [] }, status: :unprocessable_content
end

#model_graphObject

GET /mbeditor/model_graph — ActiveRecord models and their associations.

Cached until a model or migration file changes; refresh=1 forces a rebuild. Generating it eager-loads the host app, which is why this is only requested when the Models tab is opened.



763
764
765
766
767
768
769
# File 'app/controllers/mbeditor/editors_controller.rb', line 763

def model_graph
  ModelGraphService.invalidate(workspace_root) if params[:refresh].present?
  render json: ModelGraphService.call(workspace_root)
rescue StandardError => e
  render json: { ok: false, error: e.message, models: [], edges: [] },
         status: :unprocessable_content
end

#model_schemaObject

GET /mbeditor/model_schema?model=User Returns the db/schema.rb table definition for the named model as JSON. 404 when the schema file is missing or the table is not found.



1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'app/controllers/mbeditor/editors_controller.rb', line 1222

def model_schema
  model_name = params[:model].to_s.strip
  return render json: { error: "model required" }, status: :bad_request if model_name.blank?
  # SchemaService derives a file path from this name, so it is validated the
  # same way #module_members validates its own: a constant name, nothing that
  # could carry a "..".
  return render json: { error: "Invalid model" }, status: :bad_request \
    unless model_name.match?(/\A[A-Z][A-Za-z0-9_:]*\z/)

  schema = SchemaService.new(model_name, workspace_root.to_s).call
  if schema
    render json: schema
  else
    hint = " (Check if the model has a custom table_name or if db/schema.rb exists)"
    render json: { error: "No schema found for '#{model_name}'#{hint}" }, status: :not_found
  end
end

#module_membersObject

GET /mbeditor/module_members?name=ArticlesHelper Returns methods defined in the workspace file that defines the named module/class.



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'app/controllers/mbeditor/editors_controller.rb', line 788

def module_members
  name = params[:name].to_s.strip
  return render json: { error: "Invalid name" }, status: :bad_request \
    unless name.match?(/\A[A-Z][a-zA-Z0-9_]*\z/)

  excl_patterns = Array(Mbeditor.configuration.excluded_paths).map(&:to_s).reject(&:blank?)
  file = RubyDefinitionService.module_defined_in(
    workspace_root, name,
    excluded_paths: excl_patterns,
    included_dirs:  ruby_def_include_dirs
  )
  return render json: { name: name, methods: [] } unless file

  defs    = RubyDefinitionService.defs_in_file(file)
  methods = defs.flat_map do |method_name, entries|
    entries.map { |e| { name: method_name, line: e[:line], signature: e[:signature], file: relative_path(file) } }
  end
  render json: { name: name, file: relative_path(file), methods: methods }
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#monaco_assetObject

GET /mbeditor/monaco-editor/*asset_path — serve packaged Monaco files



922
923
924
925
926
927
928
929
930
931
932
# File 'app/controllers/mbeditor/editors_controller.rb', line 922

def monaco_asset
  # path_info is the path within the engine, e.g. "/monaco-editor/monaco.js"
  relative = request.path_info.delete_prefix("/")
  path = resolve_monaco_asset_path(relative)
  return head :not_found unless path

  # ~14 MB of bundle, re-sent on every page load without this.
  return unless stale?(last_modified: File.mtime(path), public: false)

  send_file path, disposition: "inline", type: Mime::Type.lookup_by_extension(File.extname(path).delete_prefix(".")) || "application/octet-stream"
end

#pingObject

GET /mbeditor/ping — heartbeat for the frontend connectivity check Silence the log line so development consoles are not spammed.



82
83
84
# File 'app/controllers/mbeditor/editors_controller.rb', line 82

def ping
  Rails.logger.silence { render json: { ok: true } }
end

#prune_branch_statesObject

POST /mbeditor/prune_branch_states — remove states for deleted branches



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'app/controllers/mbeditor/editors_controller.rb', line 178

def prune_branch_states
  root = workspace_root.to_s
  out, status = GitService.run_git(root, "branch", "--format=%(refname:short)")
  return render json: { pruned: [] } unless status.success?

  local_branches = out.split("\n").map(&:strip).reject(&:empty?)
  pruned = editor_state_service.prune_branch_states(active_branches: local_branches)

  hist_dir = workspace_root.join('tmp', 'mbeditor_history')
  if File.directory?(hist_dir)
    Dir.glob(File.join(hist_dir, '*.json')) do |hist_file|
      data = begin
        JSON.parse(File.read(hist_file))
      rescue JSON::ParserError => e
        Rails.logger.error("[mbeditor] prune_branch_states: skipping corrupt history file #{hist_file}: #{e.message}")
        nil
      end
      next unless data.is_a?(Hash) && data['branch']
      FileUtils.rm_f(hist_file) unless local_branches.include?(data['branch'])
    end
  end

  render json: { pruned: pruned }
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#pwa_iconObject

GET /mbeditor/mbeditor-icon.svg — PWA icon



963
964
965
966
967
968
969
# File 'app/controllers/mbeditor/editors_controller.rb', line 963

def pwa_icon
  path = Mbeditor::Engine.root.join("public", "mbeditor-icon.svg").to_s
  return render plain: "Not found", status: :not_found unless File.file?(path)
  return unless stale?(last_modified: File.mtime(path), public: false)

  send_file path, disposition: "inline", type: "image/svg+xml"
end

#pwa_manifestObject

GET /mbeditor/manifest.webmanifest — PWA manifest



935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
# File 'app/controllers/mbeditor/editors_controller.rb', line 935

def pwa_manifest
  base = mbeditor_base_path
  manifest = {
    name: "Mbeditor — #{Rails.root.basename}",
    short_name: "Mbeditor",
    description: "Mini Browser Editor",
    start_url: "#{base}/",
    scope: "#{base}/",
    display: "standalone",
    background_color: "#1e1e2e",
    theme_color: "#1e1e2e",
    icons: [
      { src: "#{base}/mbeditor-icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any maskable" }
    ]
  }
  render plain: JSON.generate(manifest), content_type: "application/manifest+json"
end

#pwa_swObject

GET /mbeditor/sw.js — minimal PWA service worker



954
955
956
957
958
959
960
# File 'app/controllers/mbeditor/editors_controller.rb', line 954

def pwa_sw
  path = Mbeditor::Engine.root.join("public", "sw.js").to_s
  return render plain: "Not found", status: :not_found unless File.file?(path)
  return unless stale?(last_modified: File.mtime(path), public: false)

  send_file path, disposition: "inline", type: "application/javascript"
end

#quick_fixObject

POST /mbeditor/quick_fix — autocorrect the buffer with rubocop -A and return the diff as a text edit

Runs a full rubocop -A pass on the in-memory buffer content (not the file on disk). Using a full pass (rather than --only ) means coupled cops like Layout/EmptyLineAfterMagicComment are also applied in the same round, so the result is always a clean, lint-passing state. The minimal line diff returned to Monaco keeps the edit tight.

Params:

path     - workspace-relative file path (used to derive the filename for rubocop)
code     - current file content as a string
cop_name - the cop the user clicked on (used only for the action label; not passed to rubocop)

Returns:

{ fix: { startLine, startCol, endLine, endCol, replacement } }
or { fix: null } when rubocop produced no change


1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
# File 'app/controllers/mbeditor/editors_controller.rb', line 1070

def quick_fix
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path

  cop_name = params[:cop_name].to_s.strip
  return render json: { error: "cop_name required" }, status: :unprocessable_content if cop_name.empty?
  return render json: { error: "Invalid cop name" }, status: :unprocessable_content unless cop_name.match?(/\A[\w\/]+\z/)

  code = params[:code].to_s
  ext  = File.extname(File.basename(path))

  # Use a workspace-local tempfile so RuboCop's config discovery walks up
  # from the source file's directory and finds the host app's .rubocop.yml.
  Tempfile.create([".mbeditor_fix_", ext], File.dirname(path)) do |f|
    f.write(code)
    f.flush
    tmpfile = f.path

    cmd = AvailabilityProbe.rubocop_command(workspace_root) + [AvailabilityProbe.rubocop_server_flag(workspace_root), "-A", "--no-color", tmpfile]
    env = { 'RUBOCOP_CACHE_ROOT' => File.join(Dir.tmpdir, 'rubocop') }
    status = run_lint_command(env, cmd)[:exit_status]

    # exit 0 = no offenses, exit 1 = offenses corrected, exit 2 = error
    unless status.success? || status.exitstatus == 1
      return render json: { fix: nil }
    end

    corrected = File.read(tmpfile, encoding: "UTF-8", invalid: :replace, undef: :replace)
    fix = compute_text_edit(code, corrected)
    render json: { fix: fix }
  end
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#rawObject

GET /mbeditor/raw?path=... — send raw file directly (for images)

?download=1 flips the disposition to attachment, which is the whole of the explorer's "Download" action: the browser's own save dialog does the rest, so there is no separate endpoint and no client-side blob.



362
363
364
365
366
367
368
369
370
371
372
# File 'app/controllers/mbeditor/editors_controller.rb', line 362

def raw
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path
  return render json: { error: "Not found" }, status: :not_found unless File.file?(path)

  stat = File.stat(path)
  return render_file_too_large(stat.size) if stat.size > FileOperationService::MAX_FILE_SIZE_BYTES
  return unless stale?(last_modified: stat.mtime, public: false)

  send_file path, disposition: params[:download].present? ? "attachment" : "inline"
end

GET /mbeditor/related_files?path=...



1203
1204
1205
1206
1207
1208
1209
1210
# File 'app/controllers/mbeditor/editors_controller.rb', line 1203

def related_files
  path = resolve_path(params[:path])
  return render json: {}, status: :bad_request unless path
  rel = relative_path(path)
  custom = Array(Mbeditor.configuration.related_files_custom_paths)
  result = RailsRelatedFilesService.find(workspace_root.to_s, rel, custom_paths: custom)
  render json: result
end

#renameObject

PATCH /mbeditor/rename — rename file or directory



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'app/controllers/mbeditor/editors_controller.rb', line 459

def rename
  old_path = resolve_path(params[:path])
  new_path = resolve_path(params[:new_path])
  return render json: { error: "Forbidden" }, status: :forbidden unless old_path && new_path
  return render json: { error: "Cannot rename this path" }, status: :forbidden if path_blocked_for_operations?(old_path) || path_blocked_for_operations?(new_path)

  result = FileOperationService.new(workspace_root).rename(old_path, new_path)
  broadcast_files_changed([old_path, new_path])
  render json: result
rescue FileOperationService::PathNotFoundError
  render json: { error: "Path not found" }, status: :not_found
rescue FileOperationService::TargetExistsError
  render json: { error: "Target path already exists" }, status: :unprocessable_content
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#replace_in_filesObject

POST /mbeditor/replace_in_files Replaces a string/pattern across all matching files in the workspace. Returns { replaced_count:, files_affected:[], errors:[], partial: }



877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
# File 'app/controllers/mbeditor/editors_controller.rb', line 877

def replace_in_files
  query       = params[:query].to_s.strip
  replacement = params[:replacement].to_s
  use_regex   = params[:regex] == 'true'
  match_case  = params[:match_case] == 'true'
  whole_word  = params[:whole_word] == 'true'

  return render json: { error: "Query is required" }, status: :bad_request if query.blank?
  return render json: { error: "Query too long" }, status: :bad_request if query.length > 500

  result = SearchReplaceService.replace(
    workspace_root, query, replacement,
    use_regex: use_regex, match_case: match_case, whole_word: whole_word,
    excluded_paths: Mbeditor.configuration.excluded_paths
  )

  if result.key?(:error)
    render json: { error: result[:error] }, status: :unprocessable_content
  else
    render json: result
  end
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#routesObject

GET /mbeditor/routes?path=app/controllers/users_controller.rb

Which routes reach each action in a controller, for the inline hints the editor draws beside every def. Returns {} for anything that is not a controller rather than erroring — the client asks for every Ruby file it opens and should not have to know the convention.



1195
1196
1197
1198
1199
1200
# File 'app/controllers/mbeditor/editors_controller.rb', line 1195

def routes
  key = RouteService.controller_key(params[:path].to_s)
  return render json: { controller: nil, actions: {} } unless key

  render json: { controller: key, actions: RouteService.for_controller(key) }
end

#rubocop_runObject

POST /mbeditor/rubocop — whole-workspace rubocop run

mode=autocorrect adds -a (safe corrections only) and writes to disk, so the response doubles as the post-correction offense list.



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# File 'app/controllers/mbeditor/editors_controller.rb', line 1109

def rubocop_run
  unless AvailabilityProbe.rubocop(workspace_root)
    return render json: { ok: false, error: "RuboCop is not available", files: [] }, status: :unprocessable_content
  end

  mode = params[:mode].to_s == "autocorrect" ? :autocorrect : :check
  result = RubocopRunService.run(workspace_root, mode: mode)
  # `-a` writes to disk behind every open tab's back. No path list: a
  # whole-project run can touch anything, and the omitted-paths form makes
  # the client re-check every open tab, which is exactly what's wanted.
  broadcast_files_changed(nil, structural: false) if mode == :autocorrect && result[:ok]
  render json: result
rescue StandardError => e
  render json: { ok: false, error: e.message, files: [] }, status: :unprocessable_content
end

#ruby_lspObject

POST /mbeditor/ruby_lsp — bridge to the host's ruby-lsp process. Body: { path:, content:, line: (1-based), character: (1-based), lsp_method: } Translates LSP responses into the shapes the frontend providers already consume; { fallback: true } tells the frontend to use the legacy path.



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# File 'app/controllers/mbeditor/editors_controller.rb', line 647

def ruby_lsp
  lsp_method = RUBY_LSP_METHODS[params[:lsp_method].to_s]
  return render json: { error: "Invalid lsp_method" }, status: :bad_request unless lsp_method

  # Before resolve_path: health and restart carry no document.
  return render json: ruby_lsp_health(restart: lsp_method == :restart) if lsp_method.is_a?(Symbol)

  path = resolve_path(params[:path])
  return render json: { error: "Invalid path" }, status: :bad_request unless path

  content = params[:content].to_s
  if content.bytesize > FileOperationService::MAX_FILE_SIZE_BYTES
    return render json: { error: "Content too large" }, status: :content_too_large
  end

  unless AvailabilityProbe.ruby_lsp(workspace_root)
    return render json: { error: "ruby-lsp unavailable",
                          reason: ruby_lsp_unavailable_reason,
                          rubyLspAvailable: false }, status: :unprocessable_content
  end

  positionless = RUBY_LSP_POSITIONLESS.include?(lsp_method)
  extra = if positionless
    {}
  else
    # Monaco positions are 1-based; LSP positions are 0-based.
    { position: { line: [params[:line].to_i - 1, 0].max,
                  character: [params[:character].to_i - 1, 0].max } }
  end
  per_method = RUBY_LSP_EXTRA_PARAMS[lsp_method]
  per_method = per_method.call(params) if per_method.respond_to?(:call)
  extra = extra.merge(per_method || {})
  # Only the two RuboCop-backed requests pay its boot cost; documentSymbol,
  # foldingRange and the rest are a single Prism parse and want the normal
  # budget.
  timeout = RUBY_LSP_RUBOCOP_METHODS.include?(lsp_method) ? RUBY_LSP_DIAGNOSTICS_TIMEOUT : nil

  client = RubyLspClient.for(workspace_root.to_s)
  result = client.request_with_document(lsp_method, path, content, extra, timeout: timeout)
  # The URI is what the diagnostics translator checks embedded code-action
  # edits against, so it must be the same string the client sent.
  render json: translate_ruby_lsp_result(params[:lsp_method].to_s, result, "file://#{path}")
rescue RubyLspClient::TimeoutError, RubyLspClient::NotReadyError
  # lspState lets the frontend tell "this one request was slow" from "the
  # server is dead", and stop asking in the latter case.
  render json: { fallback: true, lspState: RubyLspClient.for(workspace_root.to_s).state }
rescue StandardError => e
  render json: { error: e.message, fallback: true }
end

#ruby_renameObject

POST /mbeditor/ruby_rename — rename a Ruby constant across the workspace.

Body: { path:, content:, line:, character:, new_name:, open_paths: [] }

The workspace edit is split by whether the file is open in the editor:

- open files    -> edits returned for Monaco to apply, so the change is
                 undoable, marks the tab dirty, and respects the
                 buffer the user is actually looking at
- closed files  -> written here, then announced over the cable

That split is what makes unsaved work safe: anything dirty is by definition open, and open files are never written by the server.



719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
# File 'app/controllers/mbeditor/editors_controller.rb', line 719

def ruby_rename
  path = resolve_path(params[:path])
  return render json: { error: "Invalid path" }, status: :bad_request unless path

  new_name = params[:new_name].to_s.strip
  unless new_name.match?(RUBY_CONSTANT_PATH)
    return render json: { error: "Only Ruby constants can be renamed, and #{new_name.inspect} is not one." },
                  status: :unprocessable_content
  end

  content = params[:content].to_s
  if content.bytesize > FileOperationService::MAX_FILE_SIZE_BYTES
    return render json: { error: "Content too large" }, status: :content_too_large
  end

  unless AvailabilityProbe.ruby_lsp(workspace_root)
    return render json: { error: "ruby-lsp unavailable", reason: ruby_lsp_unavailable_reason,
                          rubyLspAvailable: false }, status: :unprocessable_content
  end

  result = RubyLspClient.for(workspace_root.to_s).request_with_document(
    "textDocument/rename", path, content,
    { position: { line: [params[:line].to_i - 1, 0].max,
                  character: [params[:character].to_i - 1, 0].max },
      newName: new_name },
    timeout: RUBY_LSP_RENAME_TIMEOUT
  )

  render json: apply_rename_changes(result, Array(params[:open_paths]).map(&:to_s))
rescue RubyLspClient::TimeoutError, RubyLspClient::NotReadyError
  render json: { error: "ruby-lsp did not answer in time", fallback: true,
                 lspState: RubyLspClient.for(workspace_root.to_s).state },
         status: :unprocessable_content
rescue StandardError => e
  # ruby-lsp raises InvalidNameError ("already in use by X") for a clash;
  # its message is the most useful thing we can show.
  render json: { error: e.message }, status: :unprocessable_content
end

#run_all_testsObject

POST /mbeditor/test_all — run the whole suite

No path: the framework's own default target applies. Deliberately a plain blocking request like /test, just with the suite ceiling — streaming would need a channel, a buffer and a cancel protocol for a button most people press a handful of times a day.



1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
# File 'app/controllers/mbeditor/editors_controller.rb', line 1131

def run_all_tests
  config = Mbeditor.configuration
  result = TestRunnerService.run_all(
    workspace_root.to_s,
    framework: config.test_framework&.to_sym,
    command: config.test_all_command,
    timeout: (config.test_all_timeout || 1800).to_i
  )
  render json: result
rescue StandardError => e
  render json: { ok: false, error: e.message }, status: :unprocessable_content
end

#run_testObject

POST /mbeditor/test — run tests for the given file



1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
# File 'app/controllers/mbeditor/editors_controller.rb', line 1145

def run_test
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path

  relative = relative_path(path)
  test_file = TestRunnerService.resolve_test_file(workspace_root.to_s, relative)
  return render json: { error: "No matching test file found for #{relative}" }, status: :not_found unless test_file

  full_test = File.join(workspace_root.to_s, test_file)
  return render json: { error: "Test file does not exist: #{test_file}" }, status: :not_found unless File.file?(full_test)

  raw_line = params[:line].to_s
  unless raw_line.empty? || raw_line.match?(/\A\d+\z/)
    return render json: { error: "Invalid line" }, status: :bad_request
  end

  # A line filter only makes sense when the user is in the test file
  # itself — running from a source file resolves to a whole test file.
  line = raw_line.empty? ? nil : raw_line.to_i
  line = nil unless line&.positive? && test_file == relative

  config = Mbeditor.configuration
  result = TestRunnerService.run(
    workspace_root.to_s,
    test_file,
    framework: config.test_framework&.to_sym,
    command: config.test_command,
    timeout: (config.test_timeout || 180).to_i,
    line: line
  )

  render json: result.merge(testFile: test_file, filteredLine: line)
rescue StandardError => e
  render json: { error: e.message, ok: false }, status: :unprocessable_content
end

#saveObject

POST /mbeditor/file — save file



375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'app/controllers/mbeditor/editors_controller.rb', line 375

def save
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path
  return render json: { error: "Cannot write to this path" }, status: :forbidden if path_blocked_for_operations?(path)

  result = FileOperationService.new(workspace_root).save(path, params[:code].to_s)
  broadcast_files_changed([path], structural: false)
  broadcast_file_saved(path)
  render json: result
rescue FileOperationService::FileTooLargeError
  render_file_too_large(params[:code].to_s.bytesize)
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#save_branch_stateObject



164
165
166
167
168
169
170
171
172
173
174
175
# File 'app/controllers/mbeditor/editors_controller.rb', line 164

def save_branch_state
  branch = sanitize_branch_name(params[:branch])
  return render json: { error: "Invalid branch name" }, status: :bad_request unless branch

  payload = params[:state].to_unsafe_h
  editor_state_service.write_branch_state(branch, payload)
  render json: { ok: true }
rescue EditorStateService::PayloadTooLargeError
  render json: { error: "State payload too large" }, status: :content_too_large
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#save_file_historyObject

POST /mbeditor/file_history



236
237
238
239
240
241
242
243
244
245
246
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
282
283
284
285
286
287
288
289
# File 'app/controllers/mbeditor/editors_controller.rb', line 236

def save_file_history
  branch = sanitize_branch_name(params[:branch])
  return render json: { error: 'Invalid branch name' }, status: :bad_request unless branch

  path = resolve_path(params[:path])
  return render json: { error: 'Forbidden' }, status: :forbidden unless path

  rel      = relative_path(path)
  new_ops  = params[:ops]
  return render json: { error: 'ops must be an array' }, status: :bad_request unless new_ops.is_a?(Array)
  return head :no_content if new_ops.empty?

  new_ops_clean = new_ops.map { |op| Array(op).first(5) }

  hist = history_file_path(branch, rel)
  FileUtils.mkdir_p(File.dirname(hist))

  File.open(hist, File::RDWR | File::CREAT) do |f|
    flock_exclusive_with_timeout!(f)
    existing = f.size > 0 ? (JSON.parse(f.read) rescue {}) : {}

    if existing.empty?
      # An empty base is a legitimate one, and in practice the usual one:
      # the client starts tracking when the editor mounts, which is before
      # the file content has arrived, so the load itself is recorded as the
      # first op against an empty document. Rejecting "" meant the initial
      # POST for every file 400'd and no history was ever written at all.
      # Only an absent base is an error.
      unless params.key?(:base)
        return render json: { error: 'base required for initial history' }, status: :bad_request
      end

      base = params[:base].to_s
      return render json: { error: 'base too large' }, status: :content_too_large if base.bytesize > STATE_MAX_BYTES
      existing = { 'branch' => branch, 'path' => rel, 'base' => base, 'ops' => [], 't' => Time.now.utc.iso8601 }
    end

    existing['ops'] = (existing['ops'] || []) + new_ops_clean
    existing['t']   = Time.now.utc.iso8601

    if existing['ops'].length > HISTORY_MAX_OPS
      to_compact       = existing['ops'].shift(HISTORY_COMPACT_TARGET)
      existing['base'] = compact_history_ops(existing['base'], to_compact)
    end

    f.truncate(0)
    f.rewind
    f.write(existing.to_json)
  end

  head :no_content
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#save_stateObject

POST /mbeditor/state — save workspace state



140
141
142
143
144
145
146
147
148
149
# File 'app/controllers/mbeditor/editors_controller.rb', line 140

def save_state
  raw = params[:state]
  raw = raw.to_unsafe_h if raw.respond_to?(:to_unsafe_h)
  editor_state_service.write_state(raw)
  render json: { ok: true }
rescue EditorStateService::PayloadTooLargeError
  render json: { error: "State payload too large" }, status: :content_too_large
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#searchObject

GET /mbeditor/search?q=...&offset=0&limit=50&regex=false&match_case=false&whole_word=false



838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'app/controllers/mbeditor/editors_controller.rb', line 838

def search
  query      = params[:q].to_s.strip
  offset     = [params[:offset].to_i, 0].max
  limit      = [[params[:limit].to_i > 0 ? params[:limit].to_i : 50, 200].min, 1].max
  use_regex  = params[:regex] == 'true'
  match_case = params[:match_case] == 'true'
  whole_word = params[:whole_word] == 'true'
  needed     = offset + limit + 1   # collect one extra to detect has_more

  return render json: [] if query.blank?
  return render json: { error: "Query too long" }, status: :bad_request if query.length > 500

  # Optional single-file scope, used by the live result refresh after a save.
  if params[:path].present?
    full = resolve_path(params[:path])
    return render json: { error: "Invalid path" }, status: :forbidden unless full

    results = SearchReplaceService.search(workspace_root, query, limit: needed,
                                          use_regex: use_regex, match_case: match_case, whole_word: whole_word,
                                          excluded_paths: Mbeditor.configuration.excluded_paths, paths: [full])
    return render json: { results: results, has_more: false }
  end

  # One subprocess per query: the full (capped) result set is collected and
  # briefly cached, so pagination and the total count come from memory.
  page = SearchReplaceService.search_page(workspace_root, query, offset: offset, limit: limit,
                                          use_regex: use_regex, match_case: match_case, whole_word: whole_word,
                                          excluded_paths: Mbeditor.configuration.excluded_paths)
  response = { results: page[:results], has_more: page[:has_more], partial: page[:partial] }
  response[:total_count] = page[:total_count] if page[:total_count]

  render json: response
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#showObject

GET /mbeditor/file?path=...



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'app/controllers/mbeditor/editors_controller.rb', line 292

def show
  path = resolve_path(params[:path])
  return render json: { error: "Forbidden" }, status: :forbidden unless path

  unless File.file?(path)
    return render json: missing_file_payload(params[:path]) if allow_missing_file?

    return render json: { error: "Not found" }, status: :not_found
  end

  start_line = params[:start_line] ? params[:start_line].to_i : nil
  line_count  = params.key?(:line_count) ? params[:line_count].to_i : 500
  line_count  = [line_count, 5000].min

  if start_line
    stat = File.stat(path)
    total_bytes = stat.size
    cached_total = self.class.cached_total_lines(path, stat.mtime.to_f)
    chunk = []
    total_lines = 0
    File.foreach(path, encoding: "UTF-8", invalid: :replace, undef: :replace) do |line|
      chunk << line if total_lines >= start_line && chunk.length < line_count
      total_lines += 1
      # Once the requested window is filled and the total is already known
      # from a prior read of this (path, mtime), skip the rest of the file.
      if cached_total && chunk.length >= line_count
        total_lines = cached_total
        break
      end
    end
    self.class.store_total_lines(path, stat.mtime.to_f, total_lines) unless cached_total
    return render json: {
      path:        relative_path(path),
      content:     chunk.join,
      truncated:   total_lines > start_line + chunk.length,
      start_line:  start_line,
      line_count:  chunk.length,
      total_lines: total_lines,
      total_bytes: total_bytes
    }
  end

  size = File.size(path)
  return render_file_too_large(size) if size > FileOperationService::MAX_FILE_SIZE_BYTES

  if image_path?(path)
    return render json: {
      path: relative_path(path),
      image: true,
      size: size,
      content: ""
    }
  end

  stat = File.stat(path)
  etag = "#{stat.mtime.to_i}-#{stat.size}"

  if stale?(etag: etag, public: false)
    content = File.read(path, encoding: "UTF-8", invalid: :replace, undef: :replace)
    render json: { path: relative_path(path), content: content }
  end
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#stateObject

GET /mbeditor/state — load workspace state



131
132
133
134
135
# File 'app/controllers/mbeditor/editors_controller.rb', line 131

def state
  render json: editor_state_service.read_state
rescue StandardError => e
  render json: { error: e.message }, status: :unprocessable_content
end

#workspaceObject

GET /mbeditor/workspace — metadata about current workspace root



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'app/controllers/mbeditor/editors_controller.rb', line 87

def workspace
  warm_ruby_definition_cache
  render json: {
    rootName: workspace_root.basename.to_s,
    rootPath: workspace_root.to_s,
    rubocopAvailable: AvailabilityProbe.rubocop(workspace_root),
    rubocopConfigPath: rubocop_config_path,
    hamlLintAvailable: AvailabilityProbe.haml_lint(workspace_root),
    gitAvailable: AvailabilityProbe.git(workspace_root),
    blameAvailable: AvailabilityProbe.git(workspace_root),
    redmineEnabled: Mbeditor.configuration.redmine_enabled == true,
    testAvailable: test_available?,
    # The client derives its request timeouts from these. Two independently
    # hard-coded numbers is how you get the browser aborting a run the
    # server is still happily executing, reported as a generic network
    # error instead of the server's own message.
    testTimeout: (Mbeditor.configuration.test_timeout || 180).to_i,
    testAllTimeout: (Mbeditor.configuration.test_all_timeout || 1800).to_i,
    actionCableEnabled: action_cable_enabled?,
    jsSyntaxCheckAvailable: JsSyntaxCheckService.available?,
    rubyLspAvailable: AvailabilityProbe.ruby_lsp(workspace_root),
    # "rg" | "git" | "grep". The tiers differ by 10-30x, and the usual
    # reason for a slow search is ripgrep being installed but absent from
    # the server process's PATH — which is invisible without this.
    searchBackend: SearchReplaceService.backend(workspace_root)
  }
end