mbeditor 0.14.2 → 0.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +43 -0
  3. data/app/assets/javascripts/mbeditor/application.js +5 -1
  4. data/app/assets/javascripts/mbeditor/collaboration_identity.js +4 -2
  5. data/app/assets/javascripts/mbeditor/collaboration_service.js +74 -2
  6. data/app/assets/javascripts/mbeditor/components/AiRoundTripModal.js +452 -0
  7. data/app/assets/javascripts/mbeditor/components/ChangelogView.js +1 -1
  8. data/app/assets/javascripts/mbeditor/components/CombinedFileView.js +3 -2
  9. data/app/assets/javascripts/mbeditor/components/EditorPanel.js +28 -27
  10. data/app/assets/javascripts/mbeditor/components/FileHistoryPanel.js +2 -7
  11. data/app/assets/javascripts/mbeditor/components/FileTree.js +144 -4
  12. data/app/assets/javascripts/mbeditor/components/GitPanel.js +1 -1
  13. data/app/assets/javascripts/mbeditor/components/ImportConflictModal.js +7 -68
  14. data/app/assets/javascripts/mbeditor/components/ImportDialog.js +2 -16
  15. data/app/assets/javascripts/mbeditor/components/MbeditorApp.js +340 -472
  16. data/app/assets/javascripts/mbeditor/components/ModalDialog.js +203 -0
  17. data/app/assets/javascripts/mbeditor/components/PastePlaceModal.js +1 -9
  18. data/app/assets/javascripts/mbeditor/components/Popover.js +88 -0
  19. data/app/assets/javascripts/mbeditor/components/PopupMenu.js +166 -0
  20. data/app/assets/javascripts/mbeditor/components/ProblemsPanel.js +8 -4
  21. data/app/assets/javascripts/mbeditor/components/QuickOpenDialog.js +5 -7
  22. data/app/assets/javascripts/mbeditor/components/SettingsModal.js +3 -14
  23. data/app/assets/javascripts/mbeditor/components/ShortcutHelp.js +4 -25
  24. data/app/assets/javascripts/mbeditor/components/TabBar.js +15 -32
  25. data/app/assets/javascripts/mbeditor/components/TestResultsPanel.js +2 -7
  26. data/app/assets/javascripts/mbeditor/editor_plugins.js +3 -23
  27. data/app/assets/javascripts/mbeditor/file_service.js +1 -1
  28. data/app/assets/javascripts/mbeditor/git_service.js +0 -7
  29. data/app/assets/javascripts/mbeditor/patch_select.js +156 -0
  30. data/app/assets/javascripts/mbeditor/tab_manager.js +19 -0
  31. data/app/assets/stylesheets/mbeditor/application.css +7 -110
  32. data/app/assets/stylesheets/mbeditor/editor.css +195 -192
  33. data/app/assets/stylesheets/mbeditor/glass.css +1 -1
  34. data/app/channels/mbeditor/collaboration_channel.rb +24 -5
  35. data/app/controllers/mbeditor/editors_controller.rb +75 -38
  36. data/app/controllers/mbeditor/git_controller.rb +1 -12
  37. data/app/services/mbeditor/ai_bundle_service.rb +181 -0
  38. data/app/services/mbeditor/archive_service.rb +43 -6
  39. data/app/services/mbeditor/availability_probe.rb +2 -2
  40. data/app/services/mbeditor/code_search_service.rb +1 -3
  41. data/app/services/mbeditor/collaboration_doc_store.rb +37 -1
  42. data/app/services/mbeditor/exclusion_matcher.rb +0 -4
  43. data/app/services/mbeditor/file_import_service.rb +4 -1
  44. data/app/services/mbeditor/file_operation_service.rb +3 -3
  45. data/app/services/mbeditor/git_service.rb +11 -45
  46. data/app/services/mbeditor/js_definition_service.rb +1 -0
  47. data/app/services/mbeditor/model_graph_service.rb +1 -0
  48. data/app/services/mbeditor/patch_apply_service.rb +185 -0
  49. data/app/services/mbeditor/rails_related_files_service.rb +1 -1
  50. data/app/services/mbeditor/redmine_config_error.rb +6 -0
  51. data/app/services/mbeditor/redmine_disabled_error.rb +10 -0
  52. data/app/services/mbeditor/redmine_service.rb +0 -8
  53. data/app/services/mbeditor/ruby_definition_service.rb +1 -0
  54. data/app/services/mbeditor/schema_service.rb +1 -0
  55. data/app/services/mbeditor/test_runner_service.rb +1 -1
  56. data/lib/mbeditor/rack/silence_ping_request.rb +14 -14
  57. data/lib/mbeditor/route_map.rb +5 -2
  58. data/lib/mbeditor/ruby_lsp_client.rb +7 -26
  59. data/lib/mbeditor/version.rb +1 -1
  60. data/public/monaco-editor/VERSIONS +2 -1
  61. data/public/monaco-editor/monaco.js +226 -226
  62. metadata +11 -4
  63. data/app/assets/javascripts/mbeditor/components/CommitGraph.js +0 -65
  64. data/app/services/mbeditor/git_commit_graph_service.rb +0 -62
@@ -33,6 +33,10 @@ module Mbeditor
33
33
  # this guard is only reachable if it trips first.
34
34
  IMPORT_MAX_FILES = 100
35
35
  IMPORT_MAX_TOTAL_BYTES = 50 * 1024 * 1024
36
+ # Multipart boundaries and part headers on top of the file bytes.
37
+ IMPORT_MULTIPART_OVERHEAD = 256 * 1024
38
+ RAW_AS_TEXT_EXTENSIONS = %w[.html .htm .xhtml .xml].freeze
39
+ before_action :reject_oversized_import, only: :import
36
40
 
37
41
  class << self
38
42
  # Small (path, mtime) => total-line-count cache so windowed reads of big
@@ -312,9 +316,20 @@ module Mbeditor
312
316
 
313
317
  stat = File.stat(path)
314
318
  return render_file_too_large(stat.size) if stat.size > FileOperationService::MAX_FILE_SIZE_BYTES
319
+
320
+ # A repo file served inline from the editor's own origin could script the
321
+ # write endpoints. The sandbox gives it an opaque origin (an <img> of an
322
+ # svg is unaffected), and markup types are shown as text, not rendered.
323
+ response.headers["Content-Security-Policy"] = "sandbox"
324
+ response.headers["X-Content-Type-Options"] = "nosniff"
315
325
  return unless stale?(last_modified: stat.mtime, public: false)
316
326
 
317
- send_file path, disposition: params[:download].present? ? "attachment" : "inline"
327
+ if params[:download].present?
328
+ send_file path, disposition: "attachment"
329
+ else
330
+ as_text = RAW_AS_TEXT_EXTENSIONS.include?(File.extname(path).downcase)
331
+ send_file path, disposition: "inline", **(as_text ? { type: "text/plain" } : {})
332
+ end
318
333
  end
319
334
 
320
335
  # GET /mbeditor/archive?paths[]=a&paths[]=b — bundle a multi-selection of
@@ -329,9 +344,8 @@ module Mbeditor
329
344
 
330
345
  resolved = requested.map { |p| resolve_path(p) }
331
346
  return render json: { error: "Forbidden" }, status: :forbidden if resolved.any?(&:nil?)
332
- unless resolved.all? { |p| File.exist?(p) || File.symlink?(p) }
333
- return render json: { error: "Not found" }, status: :not_found
334
- end
347
+ missing = first_missing(requested, resolved)
348
+ return render json: { error: "Not found: #{missing}" }, status: :not_found if missing
335
349
 
336
350
  name = File.basename(resolved.length == 1 ? resolved.first : workspace_root.to_s)
337
351
  send_data ArchiveService.new(workspace_root).build(resolved),
@@ -342,6 +356,49 @@ module Mbeditor
342
356
  render json: { error: e.message }, status: :unprocessable_content
343
357
  end
344
358
 
359
+ # GET /mbeditor/ai_bundle?paths[]=a — the selection as one text file for a
360
+ # web chat; prompt=1 returns only the message to paste alongside it.
361
+ def ai_bundle
362
+ bundle_name = "#{File.basename(workspace_root.to_s)}-bundle.md"
363
+ return render plain: AiBundleService.prompt(bundle_name) if params[:prompt].present?
364
+
365
+ requested = Array(params[:paths]).map(&:to_s).reject(&:blank?)
366
+ return render json: { error: "No paths given" }, status: :bad_request if requested.empty?
367
+
368
+ resolved = requested.map { |p| resolve_path(p) }
369
+ return render json: { error: "Forbidden" }, status: :forbidden if resolved.any?(&:nil?)
370
+ missing = first_missing(requested, resolved)
371
+ return render json: { error: "Not found: #{missing}" }, status: :not_found if missing
372
+
373
+ bundle = AiBundleService.new(workspace_root).build(resolved)
374
+ response.headers["X-Mbeditor-Bundle-Files"] = bundle[:files].to_s
375
+ response.headers["X-Mbeditor-Bundle-Bytes"] = bundle[:bytes].to_s
376
+ send_data bundle[:markdown], type: "text/markdown", disposition: "attachment", filename: bundle_name
377
+ rescue AiBundleService::LimitExceededError => e
378
+ render json: { error: e.message }, status: :content_too_large
379
+ rescue StandardError => e
380
+ render json: { error: e.message }, status: :unprocessable_content
381
+ end
382
+
383
+ # POST /mbeditor/apply_patch — JSON { patch:, check: } where check (the
384
+ # default) validates and lists the files without writing anything. Non-GET,
385
+ # so verify_mbeditor_client guards it.
386
+ def apply_patch
387
+ check = ActiveModel::Type::Boolean.new.cast(params.fetch(:check, true))
388
+ root = workspace_root.to_s
389
+ result = PatchApplyService.new(workspace_root).call(
390
+ params[:patch].to_s, check: check, blocked: ->(rel) { path_blocked_for_operations?(File.join(root, rel)) }
391
+ )
392
+ unless check
393
+ rels = result[:files].flat_map { |f| [f[:path], f[:from]] }.compact
394
+ broadcast_files_changed(rels.map { |p| File.join(root, p) })
395
+ CollaborationChannel.files_written(rels)
396
+ end
397
+ render json: result
398
+ rescue PatchApplyService::Error => e
399
+ render json: { error: e.message }, status: :unprocessable_content
400
+ end
401
+
345
402
  # POST /mbeditor/file — save file
346
403
  def save
347
404
  path = resolve_path(params[:path])
@@ -420,6 +477,7 @@ module Mbeditor
420
477
 
421
478
  written = result[:imported].map { |e| File.join(workspace_root.to_s, e[:path]) }
422
479
  broadcast_files_changed(written) if written.any?
480
+ CollaborationChannel.files_written(result[:imported].map { |e| e[:path] })
423
481
 
424
482
  render json: result
425
483
  rescue StandardError => e
@@ -570,9 +628,7 @@ module Mbeditor
570
628
  "formatting" => "textDocument/formatting",
571
629
  "signature_help" => "textDocument/signatureHelp",
572
630
  "selection_range" => "textDocument/selectionRange",
573
- "prepare_rename" => "textDocument/prepareRename",
574
- "health" => :health,
575
- "restart" => :restart
631
+ "prepare_rename" => "textDocument/prepareRename"
576
632
  }.freeze
577
633
 
578
634
  # Symbol counterpart of RUBY_LSP_METHODS' keys, for the audit log. Every
@@ -623,9 +679,6 @@ module Mbeditor
623
679
  lsp_method = RUBY_LSP_METHODS[params[:lsp_method].to_s]
624
680
  return render json: { error: "Invalid lsp_method" }, status: :bad_request unless lsp_method
625
681
 
626
- # Before resolve_path: health and restart carry no document.
627
- return render json: ruby_lsp_health(restart: lsp_method == :restart) if lsp_method.is_a?(Symbol)
628
-
629
682
  path = resolve_path(params[:path])
630
683
  return render json: { error: "Invalid path" }, status: :bad_request unless path
631
684
 
@@ -1309,6 +1362,7 @@ module Mbeditor
1309
1362
  # Everything either JS cache indexes: JsProgramService::SOURCE_EXT plus the
1310
1363
  # .erb-templated variants CodeSearchService::JS_GLOBS feeds JsGlobalsService.
1311
1364
  JS_SOURCE_NAME = /\.(js|jsx|mjs|cjs|ts|tsx)(\.erb)?\z/i
1365
+ private_constant :JS_SOURCE_NAME
1312
1366
 
1313
1367
  # Rebuilding the JS program costs ~93ms/MB, so saving a .rb file must not
1314
1368
  # throw it away. A path with no extension at all — a directory, a rename
@@ -1437,6 +1491,17 @@ module Mbeditor
1437
1491
  false
1438
1492
  end
1439
1493
 
1494
+ # The first requested (relative) path whose resolved target is missing.
1495
+ def first_missing(requested, resolved)
1496
+ requested.zip(resolved).find { |_, p| !(File.exist?(p) || File.symlink?(p)) }&.first
1497
+ end
1498
+
1499
+ def reject_oversized_import
1500
+ return if request.content_length.to_i <= IMPORT_MAX_TOTAL_BYTES + IMPORT_MULTIPART_OVERHEAD
1501
+
1502
+ render json: { error: "Drop is too large. Limit is #{human_size(IMPORT_MAX_TOTAL_BYTES)}." }, status: :content_too_large
1503
+ end
1504
+
1440
1505
  def path_blocked_for_operations?(full_path)
1441
1506
  rel = relative_path(full_path)
1442
1507
  return true if rel.blank?
@@ -1528,34 +1593,6 @@ module Mbeditor
1528
1593
  "ruby-lsp is not installed in this workspace"
1529
1594
  end
1530
1595
 
1531
- # Status for the editor's ruby-lsp indicator, and the recovery path behind
1532
- # clicking it. Never returns the resolved command — that would leak absolute
1533
- # host paths to the browser.
1534
- def ruby_lsp_health(restart: false)
1535
- if restart
1536
- # ponytail: reset! clears every probe, not just ruby-lsp. Harmless (they
1537
- # all re-probe on next use) and the alternative is a per-key API nothing
1538
- # else wants.
1539
- AvailabilityProbe.reset!
1540
- RubyLspClient.for(workspace_root.to_s).reset!
1541
- end
1542
-
1543
- available = AvailabilityProbe.ruby_lsp(workspace_root)
1544
- health = available ? RubyLspClient.for(workspace_root.to_s).health : {}
1545
-
1546
- payload = {
1547
- available: available,
1548
- disabled: Mbeditor.configuration.ruby_lsp == false,
1549
- state: health[:state] || :stopped,
1550
- restarts: health[:restarts] || 0,
1551
- error: health[:error]
1552
- }
1553
- payload[:reason] = ruby_lsp_unavailable_reason unless available
1554
- payload
1555
- rescue StandardError => e
1556
- { available: false, disabled: false, state: :failed, restarts: 0, error: e.message }
1557
- end
1558
-
1559
1596
  # Dispatches to RubyLspResultTranslator (definition/hover/completion/raw —
1560
1597
  # sanitizes every file:// URI, see that module for the trust-boundary
1561
1598
  # rationale) or to LspDiagnosticsTranslator for diagnostics, which has its
@@ -10,7 +10,6 @@ module Mbeditor
10
10
  # GET /mbeditor/git/blame ?file=<path>
11
11
  # GET /mbeditor/git/line_diff ?file=<path>
12
12
  # GET /mbeditor/git/file_history ?file=<path>
13
- # GET /mbeditor/git/commit_graph
14
13
  # GET /mbeditor/redmine/issue/:id
15
14
  class GitController < ApplicationController
16
15
  skip_before_action :verify_authenticity_token
@@ -77,14 +76,6 @@ module Mbeditor
77
76
  render json: { error: e.message }, status: :unprocessable_content
78
77
  end
79
78
 
80
- # GET /mbeditor/git/commit_graph
81
- def commit_graph
82
- commits = GitCommitGraphService.new(repo_path: workspace_root).call
83
- render json: { commits: commits }
84
- rescue StandardError => e
85
- render json: { error: e.message }, status: :unprocessable_content
86
- end
87
-
88
79
  # GET /mbeditor/git/commit_detail?sha=<hash>
89
80
  def commit_detail
90
81
  sha = params[:sha].to_s.strip
@@ -127,9 +118,7 @@ module Mbeditor
127
118
  render json: result
128
119
  rescue RedmineDisabledError => e
129
120
  render json: { error: e.message }, status: :service_unavailable
130
- rescue RedmineConfigError => e
131
- render json: { error: e.message }, status: :unprocessable_content
132
- rescue StandardError => e
121
+ rescue StandardError => e # includes RedmineConfigError
133
122
  render json: { error: e.message }, status: :unprocessable_content
134
123
  end
135
124
 
@@ -0,0 +1,181 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mbeditor
4
+ # Renders a selection of workspace files as one markdown document to hand to
5
+ # a web chat, which replies with a unified diff for PatchApplyService.
6
+ #
7
+ # The walk is ArchiveService#collect, so containment, exclusions and the
8
+ # symlink skip are identical to the tar download.
9
+ class AiBundleService
10
+ # A refusal, not a truncation: a bundle with files silently missing makes
11
+ # the assistant edit against a project it has only partly seen. Large on
12
+ # purpose: the consumer is a sandbox that greps it, not a context window.
13
+ MAX_BYTES = 64 * 1024 * 1024
14
+ BINARY_PROBE_BYTES = 8 * 1024
15
+
16
+ class LimitExceededError < StandardError; end
17
+
18
+ # Never useful to an assistant and often most of a bundle's bytes. Listed
19
+ # in the index as skipped, so the assistant knows they exist.
20
+ GENERATED = /(\A(package-lock\.json|yarn\.lock|pnpm-lock\.yaml)\z)|\.(lock|map)\z|\.min\.(js|css)\z/
21
+
22
+ # Never sent to a third-party chat. Hard-coded on purpose: a bundle is
23
+ # uploaded wholesale, so this is not something a config key should loosen.
24
+ def self.secret?(rel)
25
+ base = File.basename(rel).downcase
26
+ return true if rel.start_with?("config/credentials/") || rel.include?("/config/credentials/")
27
+ return false if %w[.env.example .env.sample].include?(base)
28
+
29
+ base == ".env" || base.start_with?(".env.") || base.start_with?("id_rsa") ||
30
+ base.end_with?(".key", ".pem", ".p12")
31
+ end
32
+
33
+ # Lossless by construction: file bytes are written exactly as they are, so a
34
+ # diff made against the unpacked copy applies to the real workspace.
35
+ #
36
+ # The pieces below feed both the bundle's own header and .prompt, so the
37
+ # two cannot drift.
38
+ UNPACK_SNIPPET = <<~'PY'
39
+ BUNDLE = "/mnt/data/bundle.md"
40
+ import os, re, subprocess
41
+ text = open(BUNDLE, encoding="utf-8", newline="").read()
42
+ hdr = re.compile(r"^=== FILE: ([^\n]+?) \((\d+) lines( no-eol)?\) ===\n", re.M)
43
+ pos = 0
44
+ while True:
45
+ m = hdr.search(text, pos)
46
+ if not m: break
47
+ end = m.end()
48
+ for _ in range(int(m.group(2))): end = text.index("\n", end) + 1
49
+ body = text[m.end():end]
50
+ if m.group(3): body = body[:-1]
51
+ pos = end
52
+ dest = os.path.join("project", m.group(1))
53
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
54
+ with open(dest, "w", encoding="utf-8", newline="") as f:
55
+ f.write(body)
56
+ def git(*a): subprocess.run(["git", *a], cwd="project", check=True)
57
+ git("init", "-q"); git("config", "core.autocrlf", "false"); git("add", "-A", "-f")
58
+ git("-c", "user.name=bundle", "-c", "user.email=bundle@example.invalid", "commit", "-qm", "base")
59
+ PY
60
+
61
+ WORKFLOW = <<~'TEXT'
62
+ - Find code with `grep -rn` and `sed -n 'A,Bp'`. Print only the lines you need.
63
+ - Edit the files in ./project.
64
+ - Reply with the `git diff` output in one ```diff block. If it is long, also save it as `changes.patch` for download.
65
+ TEXT
66
+
67
+ DIFF_RULES = "Diff rules: `diff --git a/p b/p`, `--- a/p`, `+++ b/p`; paths relative to the project root; " \
68
+ "3 lines of context; never elide or summarise lines inside a hunk; new files `--- /dev/null`; " \
69
+ "deleted files `+++ /dev/null`; no prose inside the block."
70
+
71
+ INSTRUCTIONS = "Do not read this file top to bottom. It is a source bundle.\n\n" \
72
+ "If you have a code sandbox, unpack it (set BUNDLE to the uploaded path):\n\n" \
73
+ "```python\n#{UNPACK_SNIPPET}```\n\nThen:\n#{WORKFLOW}\n" \
74
+ "With no sandbox, use the index below to pick files, and read only those between their " \
75
+ "`=== FILE: <path>` and `=== END FILE: <path> ===` lines.\n\n#{DIFF_RULES}\n"
76
+
77
+ # Paste-ready message to send with the uploaded bundle. The chat may read
78
+ # the whole file before it reaches the header, so this goes first. Needs
79
+ # only the bundle's file name; no files are read.
80
+ def self.prompt(filename)
81
+ snippet = UNPACK_SNIPPET.sub(/^BUNDLE = .*$/) { "BUNDLE = #{"/mnt/data/#{filename}".to_json}" }
82
+ "`#{filename}` is a large source bundle. Do not open, read or print it directly.\n" \
83
+ "Load it only from your code sandbox with this snippet (adjust BUNDLE if the path differs):\n\n" \
84
+ "```python\n#{snippet}```\n\nThen:\n#{WORKFLOW}\n#{DIFF_RULES}\n\nTASK: "
85
+ end
86
+
87
+ def initialize(workspace_root)
88
+ @root = workspace_root.to_s.chomp("/")
89
+ end
90
+
91
+ # +full_paths+ are absolute, already through resolve_path. Returns
92
+ # { markdown:, files:, bytes: } where +files+ counts included files.
93
+ def build(full_paths)
94
+ entries = ArchiveService.new(@root).collect(full_paths).uniq { |e| e[:name] }.sort_by { |e| e[:name] }
95
+ raise "Nothing to bundle" if entries.empty?
96
+
97
+ skipped = []
98
+ wanted = []
99
+ entries.each do |e|
100
+ e = e.merge(name: utf8(e[:name]))
101
+ reason = skip_reason(e[:name])
102
+ reason ? skipped << e.merge(reason: reason) : wanted << e
103
+ end
104
+
105
+ # Only text counts toward the cap: a binary that is never written to the
106
+ # bundle must not make the selection "too large".
107
+ texty = []
108
+ wanted.each { |e| binary?(e) ? skipped << e.merge(reason: "binary or not UTF-8") : texty << e }
109
+ total = texty.sum { |e| e[:size] }
110
+ if total > MAX_BYTES
111
+ raise LimitExceededError,
112
+ "Selection is too large (#{human(total)}). Limit is #{human(MAX_BYTES)}."
113
+ end
114
+
115
+ included = []
116
+ texty.each do |e|
117
+ text = read_text(e)
118
+ text ? included << [e[:name], text] : skipped << e.merge(reason: "binary or not UTF-8")
119
+ end
120
+
121
+ markdown = render(included, skipped.sort_by { |e| e[:name] })
122
+ { markdown: markdown, files: included.length, bytes: markdown.bytesize }
123
+ end
124
+
125
+ private
126
+
127
+ # A name with a line break would forge a bundle header; names are listed
128
+ # escaped instead of being bundled.
129
+ def skip_reason(name)
130
+ if self.class.secret?(name) then "secret"
131
+ elsif name.match?(/[\r\n]/) then "unsafe name"
132
+ elsif GENERATED.match?(File.basename(name)) then "generated"
133
+ end
134
+ end
135
+
136
+ # Names come off the filesystem in default_external, which is US-ASCII when
137
+ # LANG is unset; tag them UTF-8 so they join the UTF-8 document.
138
+ def utf8(str)
139
+ str.dup.force_encoding(Encoding::UTF_8).scrub
140
+ end
141
+
142
+ def binary?(entry)
143
+ File.open(entry[:path], "rb") { |f| f.read(BINARY_PROBE_BYTES).to_s.include?("\0") }
144
+ rescue SystemCallError => e
145
+ raise ArchiveService.read_error(entry[:name], e)
146
+ end
147
+
148
+ def read_text(entry)
149
+ data = File.binread(entry[:path])
150
+ data.force_encoding(Encoding::UTF_8)
151
+ data.valid_encoding? ? data : nil
152
+ rescue SystemCallError => e
153
+ raise ArchiveService.read_error(entry[:name], e)
154
+ end
155
+
156
+ def render(included, skipped)
157
+ out = +"# #{utf8(File.basename(@root))}\n\n## Instructions\n\n#{INSTRUCTIONS}\n## Index\n\n"
158
+ included.each { |name, text| out << "- #{name} (#{line_count(text)} lines, #{text.bytesize} bytes)\n" }
159
+ skipped.each do |e|
160
+ label = e[:name].match?(/[\r\n]/) ? e[:name].inspect : e[:name]
161
+ detail = e[:reason] == "secret" ? "secret" : "#{e[:reason]}, #{human(e[:size])}"
162
+ out << "- #{label} skipped (#{detail})\n"
163
+ end
164
+ out << "\n"
165
+ included.each do |name, text|
166
+ eol = text.empty? || text.end_with?("\n")
167
+ out << "=== FILE: #{name} (#{line_count(text)} lines#{" no-eol" unless eol}) ===\n" \
168
+ "#{text}#{"\n" unless eol}=== END FILE: #{name} ===\n"
169
+ end
170
+ out
171
+ end
172
+
173
+ def line_count(text)
174
+ text.empty? ? 0 : text.count("\n") + (text.end_with?("\n") ? 0 : 1)
175
+ end
176
+
177
+ def human(bytes)
178
+ ActiveSupport::NumberHelper.number_to_human_size(bytes)
179
+ end
180
+ end
181
+ end
@@ -23,8 +23,23 @@ module Mbeditor
23
23
 
24
24
  class LimitExceededError < StandardError; end
25
25
 
26
+ # A message safe to show: names the workspace-relative path and never the
27
+ # absolute one that Errno messages carry.
28
+ class Error < StandardError; end
29
+
30
+ def self.read_error(rel, err)
31
+ Error.new("Cannot read #{rel}: #{SystemCallError.new(nil, err.errno).message}")
32
+ end
33
+
26
34
  def initialize(workspace_root)
27
35
  @root = workspace_root.to_s.chomp("/")
36
+ # Named paths are checked against the real root: a symlinked ancestor
37
+ # (macOS /tmp, a linked-in directory) makes lexical comparison unreliable.
38
+ @real_root = begin
39
+ File.realpath(@root)
40
+ rescue SystemCallError
41
+ @root
42
+ end
28
43
  @matcher = ExclusionMatcher.new(Mbeditor.configuration.excluded_paths, root: @root)
29
44
  end
30
45
 
@@ -48,13 +63,16 @@ module Mbeditor
48
63
  write(entries)
49
64
  end
50
65
 
51
- private
52
-
53
- # Breadth-first walk of the selection, yielding regular files only.
66
+ # Breadth-first walk of the selection, yielding regular files only. Public
67
+ # so AiBundleService reuses the containment, exclusion and symlink rules.
54
68
  def collect(full_paths)
55
69
  entries = []
56
70
  seen_dirs = {}
57
- queue = full_paths.dup
71
+ # A named path inside a symlinked directory passes the lexical check and
72
+ # lstat only inspects the leaf, so the real location is compared too. Only
73
+ # named paths need it: the walk never descends into a symlink.
74
+ queue = full_paths.select { |p| real_inside?(p) }
75
+ path = nil
58
76
 
59
77
  until queue.empty?
60
78
  path = queue.shift
@@ -95,6 +113,17 @@ module Mbeditor
95
113
  end
96
114
 
97
115
  entries
116
+ rescue SystemCallError => e
117
+ raise self.class.read_error(path ? relative(path) : "", e)
118
+ end
119
+
120
+ private
121
+
122
+ def real_inside?(path)
123
+ real = File.realpath(File.symlink?(path) ? File.dirname(path) : path)
124
+ real == @real_root || real.start_with?("#{@real_root}/")
125
+ rescue SystemCallError
126
+ false
98
127
  end
99
128
 
100
129
  def write(entries)
@@ -106,8 +135,16 @@ module Mbeditor
106
135
  # TarWriter bounds the entry to the size it was given, so a file
107
136
  # that changed since it was stat-ed would otherwise write a short
108
137
  # or over-long member.
109
- data = File.binread(entry[:path])
110
- tar.add_file_simple(entry[:name], entry[:mode], data.bytesize) { |io| io.write(data) }
138
+ data = begin
139
+ File.binread(entry[:path])
140
+ rescue SystemCallError => e
141
+ raise self.class.read_error(entry[:name], e)
142
+ end
143
+ begin
144
+ tar.add_file_simple(entry[:name], entry[:mode], data.bytesize) { |io| io.write(data) }
145
+ rescue Gem::Package::TooLongFileName
146
+ raise Error, "Path is too long for a tar archive (#{entry[:name].bytesize} bytes, limit 256): #{entry[:name]}"
147
+ end
111
148
  end
112
149
  end
113
150
  end
@@ -29,7 +29,7 @@ module Mbeditor
29
29
 
30
30
  begin
31
31
  [Gem.bin_path("haml_lint", "haml-lint")]
32
- rescue Gem::Exception, Gem::GemNotFoundException
32
+ rescue Gem::Exception # includes GemNotFoundException; Bundler raises the base class
33
33
  ["haml-lint"]
34
34
  end
35
35
  end
@@ -88,7 +88,7 @@ module Mbeditor
88
88
 
89
89
  begin
90
90
  [Gem.bin_path("ruby-lsp", "ruby-lsp")]
91
- rescue Gem::Exception, Gem::GemNotFoundException
91
+ rescue Gem::Exception # includes GemNotFoundException; Bundler raises the base class
92
92
  ["bundle", "exec", "ruby-lsp"]
93
93
  end
94
94
  end
@@ -50,9 +50,7 @@ module Mbeditor
50
50
  out = result[:stdout].force_encoding(Encoding::UTF_8)
51
51
  out = out.scrub("�") unless out.valid_encoding?
52
52
  out.lines
53
- rescue ProcessRunner::TimeoutError
54
- []
55
- rescue StandardError
53
+ rescue StandardError # includes ProcessRunner::TimeoutError
56
54
  []
57
55
  end
58
56
 
@@ -70,6 +70,42 @@ module Mbeditor
70
70
  end
71
71
  end
72
72
 
73
+ # A server-side write (apply_patch, import) changed the file under a room.
74
+ # Every attached client notices, but only one may push the new disk content
75
+ # into the shared doc: two clients each replacing the text insert two copies,
76
+ # exactly as with the seed. +key+ identifies the new content, so a second
77
+ # client reporting the same write is refused while a different write wins.
78
+ # ponytail: in-memory only, unlike claim_seed's lock file; with several Puma
79
+ # workers two clients on different processes could both be granted.
80
+ DISK_CLAIM_TTL = 10
81
+
82
+ def claim_disk_write(path, key, now: monotonic)
83
+ MUTEX.synchronize do
84
+ room = touch(path, now)
85
+ last = room[:disk_claim]
86
+ next false if last && last[:key] == key && (now - last[:at]) < DISK_CLAIM_TTL
87
+
88
+ room[:disk_claim] = { key: key, at: now }
89
+ true
90
+ end
91
+ end
92
+
93
+ # The file was rewritten on disk. A room nobody is subscribed to still holds
94
+ # the old text for GRACE_TTL, and the next opener would late-join onto it and
95
+ # be shown (then save) the pre-write content. Drop it so that opener seeds
96
+ # from disk. A subscribed room is left alone (see #join); its clients
97
+ # reconcile through #claim_disk_write.
98
+ def discard_idle(path)
99
+ MUTEX.synchronize do
100
+ room = rooms[path]
101
+ next unless room && room[:subscribers].zero?
102
+
103
+ release_claim(path)
104
+ rooms.delete(path)
105
+ end
106
+ nil
107
+ end
108
+
73
109
  # Subscriber accounting. A room with a live subscriber must never be evicted:
74
110
  # eviction empties the server's copy while clients still hold content, and the
75
111
  # next client to attach would be granted a seed it must not perform.
@@ -78,7 +114,7 @@ module Mbeditor
78
114
  nil
79
115
  end
80
116
 
81
- def leave(path, now: monotonic)
117
+ def leave(path)
82
118
  MUTEX.synchronize do
83
119
  room = rooms[path]
84
120
  next unless room
@@ -46,10 +46,6 @@ module Mbeditor
46
46
  end
47
47
  end
48
48
 
49
- def reset_filesystem_probe!
50
- MUTEX.synchronize { @probe_cache = {} }
51
- end
52
-
53
49
  private
54
50
 
55
51
  # Asks the filesystem directly: look up a real directory under its own
@@ -81,7 +81,10 @@ module Mbeditor
81
81
  def write(target, io)
82
82
  FileUtils.mkdir_p(File.dirname(target))
83
83
  io.rewind
84
- File.open(target, "wb") { |f| IO.copy_stream(io, f) }
84
+ # Read fully before touching the target, then swap it in: copying straight
85
+ # into an overwritten file left it empty when the copy failed midway.
86
+ # Bounded by MAX_FILE_SIZE_BYTES, checked by the caller.
87
+ FileOperationService.new(@workspace_root).atomic_write(target, io.read.b)
85
88
  end
86
89
 
87
90
  # "logo.png" -> "logo 2.png" -> "logo 3.png" ...
@@ -64,8 +64,6 @@ module Mbeditor
64
64
  { ok: true, type: "file", path: relative_path(path), name: File.basename(path) }
65
65
  end
66
66
 
67
- private
68
-
69
67
  # Write through a temp file in the same directory and rename over the
70
68
  # target: a truncate-then-write loses the file outright if the process dies
71
69
  # mid-save. The symlink is resolved first — renaming onto the link itself
@@ -74,7 +72,7 @@ module Mbeditor
74
72
  target = link_target(path)
75
73
  tmp = File.join(File.dirname(target), ".#{File.basename(target)}.mbeditor-tmp")
76
74
  mode = File.stat(target).mode & 0o7777 if File.exist?(target)
77
- File.write(tmp, content)
75
+ File.binwrite(tmp, content)
78
76
  File.chmod(mode, tmp) if mode
79
77
  File.rename(tmp, target)
80
78
  rescue StandardError
@@ -82,6 +80,8 @@ module Mbeditor
82
80
  raise
83
81
  end
84
82
 
83
+ private
84
+
85
85
  def link_target(path)
86
86
  return path.to_s unless File.symlink?(path)
87
87