Class: Collavre::CreativesController

Inherits:
ApplicationController show all
Includes:
Collavre::Concerns::Exportable, Collavre::Concerns::Shareable, Collavre::Concerns::SlideViewable, Collavre::Concerns::TreeManageable, CreativePermissionGuard
Defined in:
app/controllers/collavre/creatives_controller.rb

Instance Method Summary collapse

Methods included from Collavre::Concerns::Shareable

#request_permission

Methods included from Collavre::Concerns::TreeManageable

#append_as_parent, #append_below, #children, #link_drop, #reorder, #unconvert

Methods included from Collavre::Concerns::Exportable

#export_markdown

Methods included from Collavre::Concerns::SlideViewable

#slide_view

Instance Method Details

#archiveObject



457
458
459
460
# File 'app/controllers/collavre/creatives_controller.rb', line 457

def archive
  @creative.archive!
  head :ok
end

#contextsObject



284
285
286
287
288
289
290
291
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
# File 'app/controllers/collavre/creatives_controller.rb', line 284

def contexts
  unless @creative.has_permission?(Current.user, :read)
    render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden and return
  end

  creative = @creative.effective_origin(Set.new)
  own_ids = creative.context_ids - [ creative.id ]
  inherited_ids = (creative.effective_context_ids - own_ids - [ creative.id ]).uniq
  own_creatives = Creative.where(id: own_ids).index_by(&:id)
  inherited_creatives = Creative.where(id: inherited_ids).index_by(&:id)

  disabled_ids = creative.effective_disabled_context_ids

  own = own_ids.filter_map do |cid|
    c = own_creatives[cid]
    next unless c

    { id: c.id, description: c.creative_snippet, inherited: false, disabled: disabled_ids.include?(cid) }
  end

  inherited = inherited_ids.filter_map do |cid|
    c = inherited_creatives[cid]
    next unless c

    { id: c.id, description: c.creative_snippet, inherited: true, disabled: disabled_ids.include?(cid) }
  end

  render json: {
    contexts: inherited + own,
    can_manage: creative.has_permission?(Current.user, :admin),
    disabled_self_context: creative.data&.dig("disabled_self_context") == true
  }
end

#createObject



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'app/controllers/collavre/creatives_controller.rb', line 180

def create
  result = Creatives::CreateService.new(
    creative_params: creative_params,
    user: Current.user,
    child_id: params[:child_id],
    before_id: params[:before_id],
    after_id: params[:after_id],
    tag_ids: params[:tags]
  ).call

  @creative = result.creative

  if result.success?
    render json: { id: @creative.id }
  else
    render json: { errors: result.errors }, status: :unprocessable_entity
  end
end

#destroyObject



467
468
469
470
471
472
473
474
475
476
477
# File 'app/controllers/collavre/creatives_controller.rb', line 467

def destroy
  parent = @creative.parent
  unless @creative.has_permission?(Current.user, :admin)
    redirect_to @creative, alert: t("collavre.creatives.errors.no_permission") and return
  end
  Creatives::DestroyService.new(
    creative: @creative,
    user: Current.user,
    delete_with_children: params[:delete_with_children].present?
  ).call
end

#editObject



208
209
210
211
212
213
214
215
# File 'app/controllers/collavre/creatives_controller.rb', line 208

def edit
  unless @creative.has_permission?(Current.user, :write)
    redirect_to @creative, alert: t("collavre.creatives.errors.no_permission") and return
  end
  if params[:inline]
    render partial: "inline_edit_form"
  end
end

#indexObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'app/controllers/collavre/creatives_controller.rb', line 16

def index
  respond_to do |format|
    format.html do
      # HTML only needs parent_creative for nav/title - skip expensive filtered queries
      # Must check permission to avoid leaking metadata (og:title, etc.) to unauthorized users
      if params[:id].present?
        creative = Creative.find_by(id: params[:id])
        @parent_creative = creative if creative&.has_permission?(Current.user, :read)
      end
      @creatives = []  # CSR will fetch via JSON
      @shared_list = @parent_creative ? @parent_creative.all_shared_users : []
    end
    format.json do
      # Full query only for JSON requests
      user_id_for_state = Current.user&.id
      if user_id_for_state.nil? && params[:id].present?
        # Public view: use owner's state
        target_creative = Creative.find_by(id: params[:id])
        user_id_for_state = target_creative&.effective_origin&.user_id
      end

      @expanded_state_map = if user_id_for_state
        UserCreativePreference.where(user_id: user_id_for_state, creative_id: params[:id]).first&.expanded_status || {}
      else
        {}
      end
      index_result = ::Creatives::IndexQuery.new(user: Current.user, params: params.to_unsafe_h).call
      @creatives = index_result.creatives || []
      @parent_creative = index_result.parent_creative
      @shared_creative = index_result.shared_creative
      @shared_list = index_result.shared_list
      @overall_progress = index_result.overall_progress if any_filter_active?
      @allowed_creative_ids = index_result.allowed_creative_ids
      @progress_map = index_result.progress_map

      # Set filtered_progress on parent creative if progress_map is available
      if @parent_creative && @progress_map && @progress_map.key?(@parent_creative.id.to_s)
        @parent_creative.filtered_progress = @progress_map[@parent_creative.id.to_s]
      end

      # Disable caching for filtered results to ensure fresh data
      expires_now if any_filter_active?

      if params[:simple].present?
        render json: serialize_creatives(@creatives)
      else
        @creatives_tree_json = build_tree(
          index_result.creatives,
          params: params,
          expanded_state_map: @expanded_state_map,
          level: 1,
          allowed_creative_ids: @allowed_creative_ids,
          progress_map: @progress_map
        )
        render json: { creatives: @creatives_tree_json }
      end
    end
  end
end

#newObject



166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'app/controllers/collavre/creatives_controller.rb', line 166

def new
  @creative = Creative.new
  if params[:parent_id].present?
    @parent_creative = Creative.find_by(id: params[:parent_id])
    @creative.parent = @parent_creative if @parent_creative
  end
  if params[:child_id].present?
    @child_creative = Creative.find_by(id: params[:child_id])
  end
  if params[:after_id].present?
    @after_creative = Creative.find_by(id: params[:after_id])
  end
end

#parent_suggestionsObject



199
200
201
202
203
204
205
206
# File 'app/controllers/collavre/creatives_controller.rb', line 199

def parent_suggestions
  unless @creative.has_permission?(Current.user, :read)
    render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden and return
  end

  suggestions = ::GeminiParentRecommender.new.recommend(@creative)
  render json: suggestions
end

#showObject



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'app/controllers/collavre/creatives_controller.rb', line 76

def show
  unless @creative.has_permission?(Current.user, :read)
    if Current.user
      redirect_to creatives_path, alert: t("collavre.creatives.errors.no_permission")
    else
      request_authentication
    end
    return
  end

  respond_to do |format|
    redirect_options = { id: @creative.id }
    redirect_options[:comment_id] = params[:comment_id] if params[:comment_id].present?
    format.html { redirect_to creatives_path(redirect_options) }
    format.json do
      # Use HTTP caching with ETag - must vary by user since response includes user-specific data
      # ETag must also include prompt comment and children timestamps since those are in response
      effective = @creative.effective_origin
      cache_user = Current.user&.id || "anon"

      # Include prompt comment timestamp (user-specific private comments starting with "> ")
      # Note: LIKE '> %' uses index prefix scan if available; consider dedicated prompt flag if bottleneck
      prompt_updated = if Current.user
        @creative.comments
          .where(private: true, user: Current.user)
          .where("content LIKE ?", "> %")
          .maximum(:updated_at)
      end

      # Get children stats in a single query, reuse for has_children
      # Use separate Arel.sql args so pick returns an array; unscope order to avoid Postgres aggregate error
      children_count, children_max_updated = @creative.children
        .unscope(:order)
        .pick(Arel.sql("COUNT(*)"), Arel.sql("MAX(updated_at)"))
      children_count = children_count.to_i  # Handle nil and string type-casting from adapters
      children_key = "#{children_count}-#{children_max_updated&.to_i}"

      last_modified = [
        @creative.updated_at,
        effective.updated_at,
        prompt_updated
      ].compact.max

      trigger_loop_data = @creative.data&.dig("trigger", "loop")
      parent_trigger_enabled = @creative.parent&.drop_trigger_enabled? || false

      etag = [
        "creative",
        @creative.cache_key_with_version,
        effective.cache_key_with_version,
        "user",
        cache_user,
        "prompt",
        prompt_updated&.to_i,
        "children",
        children_key,
        "trigger_v3",
        trigger_loop_data&.dig("state"),
        trigger_loop_data&.dig("current_iteration"),
        parent_trigger_enabled
      ].join(":")

      if stale?(etag: etag, last_modified: last_modified, public: false)
        root = params[:root_id] ? Creative.find_by(id: params[:root_id]) : nil
        depth = if root
                  (@creative.ancestors.count - root.ancestors.count) + 1
        else
                  @creative.ancestors.count + 1
        end
        render json: {
          id: @creative.id,
          description: @creative.effective_description,
          description_raw_html: @creative.description,
          origin_id: @creative.origin_id,
          parent_id: @creative.parent_id,
          progress: @creative.progress,
          progress_html: view_context.render_creative_progress(@creative),
          depth: depth,
          prompt: @creative.prompt_for(Current.user),
          has_children: children_count > 0,
          data: @creative.effective_origin(Set.new).data,
          trigger_loop: trigger_loop_data,
          is_trigger_task: parent_trigger_enabled,
          can_edit: @creative.has_permission?(Current.user, :write)
        }
      end
    end
  end
end

#trigger_actionObject



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
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
# File 'app/controllers/collavre/creatives_controller.rb', line 372

def trigger_action
  action = params[:action_name] || (request.content_type&.include?("json") ? request.request_parameters["action"] : params[:action])

  case action
  when "toggle_container"
    # Container toggle operates on effective_origin (where trigger config lives)
    creative = @creative.effective_origin(Set.new)
    unless creative.has_permission?(Current.user, :write)
      render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden
      return
    end

    enabled = ActiveModel::Type::Boolean.new.cast(
      request.content_type&.include?("json") ? request.request_parameters["enabled"] : params[:enabled]
    )
    data = creative.data || {}
    trigger = data["trigger"] || {}
    trigger["on_child_enter"] = enabled
    data["trigger"] = trigger
    previous_enabled = creative.drop_trigger_enabled?
    creative.update!(data: data)
    notify_drop_trigger_missing_agent!(creative) if !previous_enabled && creative.drop_trigger_enabled?
  when "start"
    # Start trigger: fires DropTriggerJob as if the child was just dropped into the container
    creative = @creative
    unless creative.has_permission?(Current.user, :write)
      render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden
      return
    end

    parent = creative.parent
    unless parent&.drop_trigger_enabled?
      render json: { error: t("collavre.drop_trigger.not_a_container") }, status: :unprocessable_entity
      return
    end

    DropTriggerJob.perform_later(parent.id, creative.id)

  when "pause", "resume", "restart"
    # Loop actions operate on the creative itself (where loop state lives)
    creative = @creative
    unless creative.has_permission?(Current.user, :write)
      render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden
      return
    end

    data = creative.data || {}
    trigger = data["trigger"] || {}
    loop_data = trigger["loop"]

    case action
    when "pause"
      if loop_data && %w[running pending_verification].include?(loop_data["state"])
        loop_data["state"] = "paused"
        trigger["loop"] = loop_data
        data["trigger"] = trigger
        creative.update!(data: data)
      end
    when "resume"
      if loop_data && %w[paused idle stuck awaiting_user].include?(loop_data["state"])
        loop_data["state"] = "running"
        trigger["loop"] = loop_data
        data["trigger"] = trigger
        creative.update!(data: data)
        post_continue_to_agent(creative, loop_data)
      end
    when "restart"
      if loop_data && %w[completed max_reached stuck].include?(loop_data["state"])
        loop_data["state"] = "running"
        loop_data["current_iteration"] = 0
        loop_data["infra_retry_count"] = 0
        trigger["loop"] = loop_data
        data["trigger"] = trigger
        creative.update!(data: data)
        post_restart_trigger(creative)
      end
    end
  else
    render json: { error: "Unknown action" }, status: :unprocessable_entity
    return
  end

  head :ok
end

#unarchiveObject



462
463
464
465
# File 'app/controllers/collavre/creatives_controller.rb', line 462

def unarchive
  @creative.unarchive!
  head :ok
end

#updateObject



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
# File 'app/controllers/collavre/creatives_controller.rb', line 217

def update
  respond_to do |format|
    permitted = creative_params.to_h
    base = @creative.effective_origin(Set.new)
    success = true
    previous_progress = base.progress
    requested_progress = permitted["progress"] || permitted[:progress]

    # Require write permission for origin content changes (description, progress, sequence)
    origin_changes = permitted.except("parent_id")
    if origin_changes.any? && !@creative.has_permission?(Current.user, :write)
      format.html { redirect_to @creative, alert: t("collavre.creatives.errors.no_permission") }
      format.json { render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden }
      next
    end

    # Handle parent_id change separately for Linked Creatives
    if @creative.origin_id.present? && permitted.key?("parent_id")
      parent_id = permitted.delete("parent_id")
      success &&= @creative.update(parent_id: parent_id)
    end

    # When updating the base (Origin), we must NOT pass origin_id.
    # Because if @creative is Linked, params might include origin_id.
    # Passing origin_id to the Origin creative causes it to fail validation (cannot changes if has origin)
    # or creates a self-cycle.
    permitted.delete("origin_id")
    permitted.delete(:origin_id)

    success &&= base.update(permitted)
    if success && requested_progress.present? && requested_progress.to_f >= 1 && previous_progress.to_f < 1
      if base.children.exists?
        base.self_and_descendants.where(origin_id: nil)
          .update_all(progress: 1.0, updated_at: Time.current)
      end
    end

    if success
      format.html { redirect_to @creative }
      format.json do
        base.reload
        response_data = {
          id: base.id,
          progress: base.progress,
          progress_html: view_context.render_creative_progress(base),
          has_children: base.children.exists?
        }
        # Build ancestor chain for progress updates (closure_tree: 1 SELECT via hierarchy table)
        ancestor_records = base.ancestors.order(:id)
        if ancestor_records.any?
          response_data[:ancestors] = ancestor_records.map do |anc|
            {
              id: anc.id,
              progress: anc.progress,
              progress_html: view_context.render_creative_progress(anc, has_children: true)
            }
          end
        end
        render json: response_data
      end
    else
      format.html { render :edit, status: :unprocessable_entity }
      format.json { render json: { errors: @creative.errors.full_messages }, status: :unprocessable_entity }
    end
  end
end

#update_contextsObject



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
# File 'app/controllers/collavre/creatives_controller.rb', line 318

def update_contexts
  creative = @creative.effective_origin(Set.new)
  unless creative.has_permission?(Current.user, :admin)
    render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden
    return
  end

  current_data = (creative.data || {}).dup
  current_data["context_ids"] = Array(params[:context_ids]).map(&:to_i) if params.key?(:context_ids)
  if params.key?(:disabled_context_ids)
    requested_disabled = Array(params[:disabled_context_ids]).map(&:to_i)
    parent_disabled = creative.parent&.effective_disabled_context_ids || []
    inherited_only = parent_disabled - creative.disabled_context_ids
    current_data["disabled_context_ids"] = requested_disabled - inherited_only
    current_data.delete("disabled_context_ids") if current_data["disabled_context_ids"].empty?
  end
  if params.key?(:disabled_self_context)
    if ActiveModel::Type::Boolean.new.cast(params[:disabled_self_context])
      current_data["disabled_self_context"] = true
    else
      current_data.delete("disabled_self_context")
    end
  end

  if creative.update(data: current_data)
    head :ok
  else
    render json: { errors: creative.errors.full_messages }, status: :unprocessable_entity
  end
end

#update_metadataObject



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'app/controllers/collavre/creatives_controller.rb', line 349

def 
  creative = @creative.effective_origin(Set.new)
  unless creative.has_permission?(Current.user, :write)
    render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden
    return
  end

  new_data = begin
    JSON.parse(params[:data])
  rescue JSON::ParserError => e
    render json: { error: "Invalid JSON: #{e.message}" }, status: :unprocessable_entity
    return
  end
  previous_enabled = creative.drop_trigger_enabled?

  if creative.update(data: new_data)
    notify_drop_trigger_missing_agent!(creative) if !previous_enabled && creative.drop_trigger_enabled?
    head :ok
  else
    render json: { errors: creative.errors.full_messages }, status: :unprocessable_entity
  end
end