context_drop 0.1.3 → 0.2.0

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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +218 -49
  3. data/SPEC.md +74 -26
  4. data/app/assets/javascripts/context_drop/context_drop.js +5227 -652
  5. data/app/controllers/context_drop/agent_controller.rb +170 -0
  6. data/app/controllers/context_drop/configs_controller.rb +2 -1
  7. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +62 -2
  8. data/app/controllers/context_drop/feedbacks_controller.rb +13 -3
  9. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  10. data/app/helpers/context_drop/dashboard_helper.rb +52 -0
  11. data/app/helpers/context_drop/widget_helper.rb +11 -1
  12. data/app/javascript/context_drop/__tests__/widget.test.ts +731 -92
  13. data/app/javascript/context_drop/api-client.ts +130 -11
  14. data/app/javascript/context_drop/element-picker.ts +247 -30
  15. data/app/javascript/context_drop/icons.ts +24 -0
  16. data/app/javascript/context_drop/markdown.ts +146 -0
  17. data/app/javascript/context_drop/sanitizer.ts +413 -2
  18. data/app/javascript/context_drop/screenshot.ts +102 -8
  19. data/app/javascript/context_drop/styles.ts +1528 -252
  20. data/app/javascript/context_drop/types.ts +147 -0
  21. data/app/javascript/context_drop/widget.ts +2629 -288
  22. data/app/models/context_drop/feedback.rb +34 -5
  23. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +166 -60
  24. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +178 -47
  25. data/app/views/layouts/context_drop/application.html.erb +416 -70
  26. data/config/routes.rb +11 -0
  27. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  28. data/lib/context_drop/agent/key_store.rb +290 -0
  29. data/lib/context_drop/agent/llm_client.rb +413 -0
  30. data/lib/context_drop/agent/orchestrator.rb +314 -0
  31. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  32. data/lib/context_drop/configuration.rb +216 -3
  33. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  34. data/lib/context_drop/mcp/environment_router.rb +115 -0
  35. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +87 -8
  36. data/lib/context_drop/mcp/remote_client.rb +120 -0
  37. data/lib/context_drop/mcp/server.rb +9 -2
  38. data/lib/context_drop/mcp/tools/get_feedback.rb +50 -4
  39. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +26 -4
  40. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  41. data/lib/context_drop/mcp/tools/list_feedbacks.rb +174 -22
  42. data/lib/context_drop/mcp/tools/update_feedback_status.rb +45 -4
  43. data/lib/context_drop/version.rb +1 -1
  44. data/lib/context_drop.rb +8 -2
  45. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  46. metadata +13 -2
@@ -0,0 +1,314 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module ContextDrop
6
+ module Agent
7
+ class Orchestrator
8
+ MAX_TOOL_ITERATIONS = 8
9
+ MAX_INLINE_IMAGE_BYTES = 4 * 1024 * 1024 # 4 MB
10
+
11
+ AGENT_TOOLS = [
12
+ {
13
+ name: "list_files",
14
+ description: "List workspace files inside the local Rails application (excluding git, secrets, and dependencies).",
15
+ parameters: {
16
+ type: "object",
17
+ properties: {
18
+ directory: { type: "string", description: "Relative directory path (default '.')." },
19
+ pattern: { type: "string", description: "Optional filename/path substring or glob filter (e.g. 'checkout' or '*.erb')." },
20
+ limit: { type: "integer", description: "Max files to return (default 150)." }
21
+ }
22
+ }
23
+ },
24
+ {
25
+ name: "read_file",
26
+ description: "Read numbered lines from a source file inside the local Rails workspace.",
27
+ parameters: {
28
+ type: "object",
29
+ required: ["path"],
30
+ properties: {
31
+ path: { type: "string", description: "Workspace-relative file path (e.g. 'app/views/layouts/application.html.erb')." },
32
+ start_line: { type: "integer", description: "1-indexed start line (default 1)." },
33
+ end_line: { type: "integer", description: "1-indexed inclusive end line (default 200)." }
34
+ }
35
+ }
36
+ },
37
+ {
38
+ name: "search_code",
39
+ description: "Search for a selector, class name, helper, route, or string across local workspace source files.",
40
+ parameters: {
41
+ type: "object",
42
+ required: ["query"],
43
+ properties: {
44
+ query: { type: "string", description: "Substring or identifier to search for (e.g. '#checkout-button')." },
45
+ directory: { type: "string", description: "Optional relative subdirectory to narrow search (e.g. 'app')." }
46
+ }
47
+ }
48
+ },
49
+ {
50
+ name: "list_feedbacks",
51
+ description: "List ContextDrop feedback submissions across local, staging, production, or all environments.",
52
+ parameters: {
53
+ type: "object",
54
+ properties: {
55
+ environment: { type: "string", description: "Environment filter: 'all' (default), 'local', 'staging', 'production', etc." },
56
+ status: { type: "string", enum: %w[new reviewed resolved dismissed], description: "Workflow status filter." },
57
+ page_url: { type: "string", description: "Originating page URL substring filter." },
58
+ query: { type: "string", description: "Free-text search across message and DOM selectors." },
59
+ limit: { type: "integer", description: "Max items (default 15)." }
60
+ }
61
+ }
62
+ },
63
+ {
64
+ name: "get_feedback",
65
+ description: "Fetch full ContextDrop feedback details and pinned DOM ElementReference snapshots by ID or '<env>:<id>'.",
66
+ parameters: {
67
+ type: "object",
68
+ required: ["id"],
69
+ properties: {
70
+ id: { type: "string", description: "Feedback ID or qualified '<env>:<id>' (e.g. 'staging:42')." },
71
+ environment: { type: "string", description: "Optional environment name." }
72
+ }
73
+ }
74
+ },
75
+ {
76
+ name: "propose_file_edit",
77
+ description: "Stage a safe file change as an interactive diff card for the developer to review and click Apply in the sidebar. Never modifies files without user approval.",
78
+ parameters: {
79
+ type: "object",
80
+ required: %w[path old_string new_string],
81
+ properties: {
82
+ path: { type: "string", description: "Workspace-relative path of the file to modify or create." },
83
+ old_string: { type: "string", description: "Exact existing lines to replace (include 2-4 surrounding lines so it matches uniquely; pass empty string '' only when creating a brand-new file)." },
84
+ new_string: { type: "string", description: "Exact replacement text." },
85
+ summary: { type: "string", description: "Short 1-line description of what this change fixes." }
86
+ }
87
+ }
88
+ }
89
+ ].freeze
90
+
91
+ def initialize(sandbox: nil, key_store: nil)
92
+ @sandbox = sandbox || WorkspaceSandbox.new
93
+ @key_store = key_store || KeyStore.new
94
+ end
95
+
96
+ def run_turn(messages:, page_url: nil, element_references: [], attachments: [], provider: nil, model: nil)
97
+ creds = @key_store.resolve_credentials!(provider: provider, model_override: model)
98
+ conversation = build_initial_conversation(messages, page_url, element_references, attachments)
99
+
100
+ tool_traces = []
101
+ proposed_edits = []
102
+ final_text = ""
103
+
104
+ MAX_TOOL_ITERATIONS.times do
105
+ step = LlmClient.complete_step(
106
+ credentials: creds,
107
+ system_prompt: build_system_prompt(page_url),
108
+ conversation: conversation,
109
+ tools: AGENT_TOOLS
110
+ )
111
+
112
+ final_text = step[:text].to_s unless step[:text].to_s.empty?
113
+ calls = Array(step[:tool_calls])
114
+ break if calls.empty?
115
+
116
+ conversation << {
117
+ role: "assistant",
118
+ content: step[:text].to_s,
119
+ raw_assistant: step[:raw_assistant]
120
+ }
121
+
122
+ tool_results = calls.map do |call|
123
+ exec = execute_tool(call[:name], call[:arguments], proposed_edits)
124
+ tool_traces << {
125
+ name: call[:name],
126
+ summary: exec[:summary],
127
+ status: exec[:is_error] ? "error" : "ok"
128
+ }
129
+ {
130
+ id: call[:id],
131
+ name: call[:name],
132
+ output: exec[:output],
133
+ is_error: exec[:is_error]
134
+ }
135
+ end
136
+
137
+ conversation << {
138
+ role: "tool_results",
139
+ results: tool_results
140
+ }
141
+ end
142
+
143
+ {
144
+ reply: final_text.empty? && proposed_edits.any? ? "I've staged #{proposed_edits.size} file change(s) below—review the diff and click **Apply Change** when ready." : final_text,
145
+ provider: creds[:provider],
146
+ model: creds[:model],
147
+ tool_calls: tool_traces,
148
+ proposed_edits: proposed_edits
149
+ }
150
+ end
151
+
152
+ private
153
+
154
+ def build_system_prompt(page_url)
155
+ envs = ContextDrop::MCP::EnvironmentRouter.available_environments.map { |e| e[:name] }.join(", ")
156
+ <<~SYS
157
+ You are the ContextDrop Local Coding Agent embedded inside a Ruby on Rails application (`#{ContextDrop.config.resolved_environment}` environment).
158
+ Current browser page URL: #{page_url || 'unknown'}
159
+ Connected ContextDrop feedback environments: #{envs}
160
+
161
+ Guidelines:
162
+ 1. Inspect relevant Rails routes (`config/routes.rb`), controllers (`app/controllers/`), views/components (`app/views/`, `app/javascript/`, `app/assets/`), or feedbacks (`list_feedbacks` / `get_feedback`) using your read-only tools before guessing.
163
+ 2. Always read the target lines of a file with `read_file` before calling `propose_file_edit` so `old_string` matches exact whitespace.
164
+ 3. `propose_file_edit` stages a non-destructive diff card in the user's sidebar—never claim a file was already written until the user clicks Apply.
165
+ 4. Keep explanations concise, concrete, and grounded in exact file paths and selectors.
166
+ SYS
167
+ end
168
+
169
+ def build_initial_conversation(raw_messages, page_url, element_references, attachments)
170
+ turns = Array(raw_messages).filter_map do |m|
171
+ next unless m.is_a?(Hash)
172
+
173
+ str_m = m.transform_keys(&:to_s)
174
+ role = str_m["role"].to_s
175
+ next unless %w[user assistant].include?(role)
176
+
177
+ text = str_m["content"].to_s.strip
178
+ next if text.empty?
179
+
180
+ { role: role, content: text }
181
+ end
182
+
183
+ raise ContextDrop::Error, "Message history cannot be empty" if turns.empty?
184
+
185
+ # Enrich the latest user message with pinned DOM ElementReference snapshots and screenshots
186
+ last_user_idx = turns.rindex { |t| t[:role] == "user" }
187
+ if last_user_idx
188
+ context_appendix = format_dom_context(page_url, element_references)
189
+ unless context_appendix.empty?
190
+ turns[last_user_idx][:content] = "#{turns[last_user_idx][:content]}\n\n#{context_appendix}"
191
+ end
192
+ turns[last_user_idx][:images] = extract_base64_images(attachments)
193
+ end
194
+
195
+ turns
196
+ end
197
+
198
+ def format_dom_context(page_url, element_references)
199
+ els = Array(element_references)
200
+ return "" if els.empty?
201
+
202
+ lines = ["---", "Pinned Live DOM Context (on `#{page_url || '/'}`):"]
203
+ els.each_with_index do |raw_el, idx|
204
+ el = ContextDrop::MetadataSanitizer.sanitize_element_reference(raw_el)
205
+ lines << "#{idx + 1}. `<#{el[:tag_name]}>` selector=`#{el[:selector]}`"
206
+ lines << " - dom_path: `#{el[:dom_path]}`" if el[:dom_path]
207
+ lines << " - text: #{el[:text_content].inspect}" if el[:text_content]
208
+ lines << " - bounding_rect: `#{JSON.generate(el[:bounding_rect])}`" if el[:bounding_rect]
209
+ lines << " - attributes: `#{JSON.generate(el[:attributes_snapshot])}`" if el[:attributes_snapshot] && !el[:attributes_snapshot].empty?
210
+ end
211
+ lines.join("\n")
212
+ end
213
+
214
+ def extract_base64_images(attachments)
215
+ Array(attachments).filter_map do |raw_att|
216
+ att = raw_att.is_a?(Hash) ? raw_att.transform_keys(&:to_s) : {}
217
+ data_url = (att["data_url"] || att["data"]).to_s.strip
218
+ next if data_url.empty?
219
+
220
+ mime = "image/png"
221
+ b64 = data_url
222
+ if data_url.include?(";base64,")
223
+ header, b64 = data_url.split(";base64,", 2)
224
+ mime = header.sub(/\Adata:/i, "").strip if header.start_with?("data:")
225
+ end
226
+
227
+ next if b64.bytesize > (MAX_INLINE_IMAGE_BYTES * 4 / 3)
228
+
229
+ { mime_type: mime, data: b64.strip }
230
+ end
231
+ end
232
+
233
+ def execute_tool(name, raw_args, proposed_edits)
234
+ args = raw_args.is_a?(Hash) ? raw_args.transform_keys(&:to_s) : {}
235
+
236
+ case name.to_s
237
+ when "list_files"
238
+ dir = args["directory"].presence || "."
239
+ res = @sandbox.list_files(directory: dir, pattern: args["pattern"], limit: args["limit"] || 150)
240
+ {
241
+ summary: "Listed files in #{dir}#{args['pattern'] ? " (#{args['pattern']})" : ''}",
242
+ output: JSON.generate(res),
243
+ is_error: false
244
+ }
245
+ when "read_file"
246
+ path = args["path"].to_s
247
+ res = @sandbox.read_file(
248
+ path: path,
249
+ start_line: args["start_line"] || 1,
250
+ end_line: args["end_line"] || 200
251
+ )
252
+ {
253
+ summary: "Read #{res[:path]} (L#{res[:start_line]}–#{res[:end_line]})",
254
+ output: JSON.generate(res),
255
+ is_error: false
256
+ }
257
+ when "search_code"
258
+ q = args["query"].to_s
259
+ res = @sandbox.search_code(query: q, directory: args["directory"].presence || ".")
260
+ {
261
+ summary: "Searched workspace for \"#{q[0, 40]}\" (#{res[:matches].size} hits)",
262
+ output: JSON.generate(res),
263
+ is_error: false
264
+ }
265
+ when "list_feedbacks"
266
+ mcp_res = ContextDrop::MCP::Tools::ListFeedbacks.call(args.merge("limit" => args["limit"] || 15))
267
+ env_lbl = args["environment"].presence || "all"
268
+ {
269
+ summary: "Queried feedbacks (#{env_lbl})",
270
+ output: mcp_res.dig(:content, 0, :text).to_s,
271
+ is_error: !!mcp_res[:isError]
272
+ }
273
+ when "get_feedback"
274
+ mcp_res = ContextDrop::MCP::Tools::GetFeedback.call(args.merge("include_images" => false))
275
+ {
276
+ summary: "Fetched feedback #{args['id']}",
277
+ output: mcp_res.dig(:content, 0, :text).to_s,
278
+ is_error: !!mcp_res[:isError]
279
+ }
280
+ when "propose_file_edit"
281
+ staged = @sandbox.stage_edit(
282
+ path: args["path"],
283
+ old_string: args["old_string"],
284
+ new_string: args["new_string"],
285
+ summary: args["summary"]
286
+ )
287
+ proposed_edits << staged
288
+ {
289
+ summary: "Proposed diff for #{staged[:path]} (+#{staged[:added_lines]} -#{staged[:removed_lines]})",
290
+ output: JSON.generate(
291
+ staged_edit_id: staged[:id],
292
+ path: staged[:path],
293
+ status: "pending_user_approval",
294
+ diff: staged[:diff]
295
+ ),
296
+ is_error: false
297
+ }
298
+ else
299
+ {
300
+ summary: "Unknown tool #{name}",
301
+ output: JSON.generate(error: "Unknown tool: #{name}"),
302
+ is_error: true
303
+ }
304
+ end
305
+ rescue StandardError => e
306
+ {
307
+ summary: "#{name} failed",
308
+ output: JSON.generate(error: e.message),
309
+ is_error: true
310
+ }
311
+ end
312
+ end
313
+ end
314
+ end