Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Dedicated image caption AI feature and agent validations (#41729)

Natalie Tay86680f6b0d4f
diff --git a/db/structure.sql b/db/structure.sql
index 575c2cb2720..9e488631c88 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -845,10 +845,10 @@ ALTER SEQUENCE public.ai_moderation_settings_id_seq OWNED BY public.ai_moderatio
--
--- Name: ai_post_image_descriptions; Type: TABLE; Schema: public; Owner: -
+-- Name: ai_post_image_captions; Type: TABLE; Schema: public; Owner: -
--
-CREATE TABLE public.ai_post_image_descriptions (
+CREATE TABLE public.ai_post_image_captions (
id bigint NOT NULL,
post_id integer NOT NULL,
upload_id integer NOT NULL,
@@ -864,10 +864,10 @@ CREATE TABLE public.ai_post_image_descriptions (
--
--- Name: ai_post_image_descriptions_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+-- Name: ai_post_image_captions_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
-CREATE SEQUENCE public.ai_post_image_descriptions_id_seq
+CREATE SEQUENCE public.ai_post_image_captions_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
@@ -876,10 +876,10 @@ CREATE SEQUENCE public.ai_post_image_descriptions_id_seq
--
--- Name: ai_post_image_descriptions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+-- Name: ai_post_image_captions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
-ALTER SEQUENCE public.ai_post_image_descriptions_id_seq OWNED BY public.ai_post_image_descriptions.id;
+ALTER SEQUENCE public.ai_post_image_captions_id_seq OWNED BY public.ai_post_image_captions.id;
--
@@ -12375,10 +12375,10 @@ ALTER TABLE ONLY public.ai_moderation_settings ALTER COLUMN id SET DEFAULT nextv
--
--- Name: ai_post_image_descriptions id; Type: DEFAULT; Schema: public; Owner: -
+-- Name: ai_post_image_captions id; Type: DEFAULT; Schema: public; Owner: -
--
-ALTER TABLE ONLY public.ai_post_image_descriptions ALTER COLUMN id SET DEFAULT nextval('public.ai_post_image_descriptions_id_seq'::regclass);
+ALTER TABLE ONLY public.ai_post_image_captions ALTER COLUMN id SET DEFAULT nextval('public.ai_post_image_captions_id_seq'::regclass);
--
@@ -14596,11 +14596,11 @@ ALTER TABLE ONLY public.ai_moderation_settings
--
--- Name: ai_post_image_descriptions ai_post_image_descriptions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+-- Name: ai_post_image_captions ai_post_image_captions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
-ALTER TABLE ONLY public.ai_post_image_descriptions
- ADD CONSTRAINT ai_post_image_descriptions_pkey PRIMARY KEY (id);
+ALTER TABLE ONLY public.ai_post_image_captions
+ ADD CONSTRAINT ai_post_image_captions_pkey PRIMARY KEY (id);
--
@@ -17173,17 +17173,17 @@ CREATE UNIQUE INDEX idx_ai_bot_conversation_stars_user_topic ON public.discourse
--
--- Name: idx_ai_post_image_descriptions_lookup; Type: INDEX; Schema: public; Owner: -
+-- Name: idx_ai_post_image_captions_lookup; Type: INDEX; Schema: public; Owner: -
--
-CREATE UNIQUE INDEX idx_ai_post_image_descriptions_lookup ON public.ai_post_image_descriptions USING btree (post_id, locale, base62_sha1);
+CREATE UNIQUE INDEX idx_ai_post_image_captions_lookup ON public.ai_post_image_captions USING btree (post_id, locale, base62_sha1);
--
--- Name: idx_ai_post_image_descriptions_reuse; Type: INDEX; Schema: public; Owner: -
+-- Name: idx_ai_post_image_captions_reuse; Type: INDEX; Schema: public; Owner: -
--
-CREATE INDEX idx_ai_post_image_descriptions_reuse ON public.ai_post_image_descriptions USING btree (base62_sha1, locale);
+CREATE INDEX idx_ai_post_image_captions_reuse ON public.ai_post_image_captions USING btree (base62_sha1, locale);
--
@@ -22648,6 +22648,9 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20260715090434'),
+('20260715090355'),
+('20260715064155'),
('20260713180615'),
('20260708095336'),
('20260708080308'),
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/post_image_captions_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/post_image_captions_controller.rb
new file mode 100644
index 00000000000..1295c8be319
--- /dev/null
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/post_image_captions_controller.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ class PostImageCaptionsController < ::ApplicationController
+ requires_plugin PLUGIN_NAME
+ requires_login
+
+ def index
+ post = find_post
+ guardian.ensure_can_edit!(post)
+
+ render json: {
+ captions:
+ DiscourseAi::PostImageCaptions.editable_captions(post, caption_locale(post)),
+ }
+ end
+
+ def update
+ post = find_post
+ guardian.ensure_can_edit!(post)
+
+ description = params[:description].to_s.strip
+
+ if description.blank?
+ return(
+ render_json_error(
+ I18n.t("discourse_ai.post_image_captions.errors.description_blank"),
+ status: :unprocessable_entity,
+ )
+ )
+ end
+
+ if description.length > DiscourseAi::PostImageCaptions::MAX_CAPTION_LENGTH
+ return(
+ render_json_error(
+ I18n.t(
+ "discourse_ai.post_image_captions.errors.description_too_long",
+ count: DiscourseAi::PostImageCaptions::MAX_CAPTION_LENGTH,
+ ),
+ status: :unprocessable_entity,
+ )
+ )
+ end
+
+ image_caption =
+ DiscourseAi::PostImageCaptions.update_caption(
+ post,
+ caption_locale(post),
+ params[:base62_sha1],
+ description,
+ )
+
+ raise Discourse::NotFound if image_caption.blank?
+
+ render json: {
+ base62_sha1: image_caption.base62_sha1,
+ description: image_caption.description,
+ }
+ end
+
+ private
+
+ def find_post
+ Post.find(params[:post_id])
+ end
+
+ def caption_locale(post)
+ params[:locale].presence || DiscourseAi::PostImageCaptions.original_locale(post)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/post_image_descriptions_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/post_image_descriptions_controller.rb
deleted file mode 100644
index e7354bcf25f..00000000000
--- a/plugins/discourse-ai/app/controllers/discourse_ai/post_image_descriptions_controller.rb
+++ /dev/null
@@ -1,74 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseAi
- class PostImageDescriptionsController < ::ApplicationController
- requires_plugin PLUGIN_NAME
- requires_login
-
- def index
- post = find_post
- guardian.ensure_can_edit!(post)
-
- render json: {
- descriptions:
- DiscourseAi::PostImageDescriptions.editable_descriptions(
- post,
- description_locale(post),
- ),
- }
- end
-
- def update
- post = find_post
- guardian.ensure_can_edit!(post)
-
- description = params[:description].to_s.strip
-
- if description.blank?
- return(
- render_json_error(
- I18n.t("discourse_ai.post_image_descriptions.errors.description_blank"),
- status: :unprocessable_entity,
- )
- )
- end
-
- if description.length > DiscourseAi::PostImageDescriptions::MAX_DESCRIPTION_LENGTH
- return(
- render_json_error(
- I18n.t(
- "discourse_ai.post_image_descriptions.errors.description_too_long",
- count: DiscourseAi::PostImageDescriptions::MAX_DESCRIPTION_LENGTH,
- ),
- status: :unprocessable_entity,
- )
- )
- end
-
- image_description =
- DiscourseAi::PostImageDescriptions.update_description(
- post,
- description_locale(post),
- params[:base62_sha1],
- description,
- )
-
- raise Discourse::NotFound if image_description.blank?
-
- render json: {
- base62_sha1: image_description.base62_sha1,
- description: image_description.description,
- }
- end
-
- private
-
- def find_post
- Post.find(params[:post_id])
- end
-
- def description_locale(post)
- params[:locale].presence || DiscourseAi::PostImageDescriptions.original_locale(post)
- end
- end
-end
diff --git a/plugins/discourse-ai/app/jobs/regular/generate_post_image_descriptions.rb b/plugins/discourse-ai/app/jobs/regular/generate_post_image_captions.rb
similarity index 61%
rename from plugins/discourse-ai/app/jobs/regular/generate_post_image_descriptions.rb
rename to plugins/discourse-ai/app/jobs/regular/generate_post_image_captions.rb
index d9423e51cfd..e8cc889004a 100644
--- a/plugins/discourse-ai/app/jobs/regular/generate_post_image_descriptions.rb
+++ b/plugins/discourse-ai/app/jobs/regular/generate_post_image_captions.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module Jobs
- class GeneratePostImageDescriptions < ::Jobs::Base
+ class GeneratePostImageCaptions < ::Jobs::Base
sidekiq_options queue: "low", retry: false
def execute(args)
@@ -11,13 +11,13 @@ module Jobs
post = Post.find_by(id: post_id)
return if post.blank?
- locale = args[:locale].presence || DiscourseAi::PostImageDescriptions.original_locale(post)
+ locale = args[:locale].presence || DiscourseAi::PostImageCaptions.original_locale(post)
DistributedMutex.synchronize(
- "generate_post_image_descriptions_#{post.id}_#{locale}",
+ "generate_post_image_captions_#{post.id}_#{locale}",
validity: 10.minutes,
) do
- DiscourseAi::PostImageDescriptions.generate_missing(
+ DiscourseAi::PostImageCaptions.generate_missing(
post,
locale: locale,
base62_sha1s: args[:base62_sha1s],
diff --git a/plugins/discourse-ai/app/jobs/scheduled/post_image_captions_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/post_image_captions_backfill.rb
new file mode 100644
index 00000000000..93377cc527f
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/post_image_captions_backfill.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module Jobs
+ class PostImageCaptionsBackfill < ::Jobs::Scheduled
+ every 15.minutes
+ cluster_concurrency 1
+ sidekiq_options retry: false
+
+ def execute(_args)
+ return if !DiscourseAi::PostImageCaptions.enabled?
+ return if !DiscourseAi::PostImageCaptions.generation_enabled?
+ return if !DiscourseAi::PostImageCaptions.credits_available?
+
+ limit = DiscourseAi::PostImageCaptions.backfill_limit
+ return if limit <= 0
+
+ DiscourseAi::PostImageCaptions
+ .backfill_targets(limit:)
+ .each do |target|
+ Jobs.enqueue(
+ :generate_post_image_captions,
+ post_id: target[:post_id],
+ locale: target[:locale],
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/post_image_descriptions_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/post_image_descriptions_backfill.rb
deleted file mode 100644
index 9acda8dc488..00000000000
--- a/plugins/discourse-ai/app/jobs/scheduled/post_image_descriptions_backfill.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-# frozen_string_literal: true
-
-module Jobs
- class PostImageDescriptionsBackfill < ::Jobs::Scheduled
- every 15.minutes
- cluster_concurrency 1
- sidekiq_options retry: false
-
- def execute(_args)
- return if !DiscourseAi::PostImageDescriptions.enabled?
- return if !DiscourseAi::PostImageDescriptions.generation_enabled?
- return if !DiscourseAi::PostImageDescriptions.credits_available?
-
- limit = DiscourseAi::PostImageDescriptions.backfill_limit
- return if limit <= 0
-
- DiscourseAi::PostImageDescriptions
- .backfill_targets(limit:)
- .each do |target|
- Jobs.enqueue(
- :generate_post_image_descriptions,
- post_id: target[:post_id],
- locale: target[:locale],
- )
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/app/models/ai_post_image_description.rb b/plugins/discourse-ai/app/models/ai_post_image_caption.rb
similarity index 72%
rename from plugins/discourse-ai/app/models/ai_post_image_description.rb
rename to plugins/discourse-ai/app/models/ai_post_image_caption.rb
index 74542c1f072..78fb5ca09aa 100644
--- a/plugins/discourse-ai/app/models/ai_post_image_description.rb
+++ b/plugins/discourse-ai/app/models/ai_post_image_caption.rb
@@ -1,13 +1,13 @@
# frozen_string_literal: true
-class AiPostImageDescription < ActiveRecord::Base
+class AiPostImageCaption < ActiveRecord::Base
belongs_to :post
belongs_to :upload
end
# == Schema Information
#
-# Table name: ai_post_image_descriptions
+# Table name: ai_post_image_captions
#
# id :bigint not null, primary key
# attempts :integer default(0), not null
@@ -23,6 +23,6 @@ end
#
# Indexes
#
-# idx_ai_post_image_descriptions_lookup (post_id,locale,base62_sha1) UNIQUE
-# idx_ai_post_image_descriptions_reuse (base62_sha1,locale)
+# idx_ai_post_image_captions_lookup (post_id,locale,base62_sha1) UNIQUE
+# idx_ai_post_image_captions_reuse (base62_sha1,locale)
#
diff --git a/plugins/discourse-ai/app/services/problem_check/ai_image_caption_agent.rb b/plugins/discourse-ai/app/services/problem_check/ai_image_caption_agent.rb
new file mode 100644
index 00000000000..dd6c86acbc9
--- /dev/null
+++ b/plugins/discourse-ai/app/services/problem_check/ai_image_caption_agent.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+class ProblemCheck::AiImageCaptionAgent < ProblemCheck
+ self.priority = "high"
+
+ def call
+ return no_problem if !SiteSetting.discourse_ai_enabled
+ return no_problem if !SiteSetting.ai_post_image_captions_enabled
+
+ agent_id = SiteSetting.ai_image_caption_agent.to_i
+ agent = AiAgent.find_by(id: agent_id)
+ return agent_problem(:agent_missing, agent_id: agent_id) if agent.blank?
+
+ agent_class = agent.class_instance
+ return agent_problem(:agent_vision_disabled, agent_id: agent_id) if !agent_class&.vision_enabled
+
+ llm_model = DiscourseAi::PostImageCaptions.image_caption_llm_model(agent)
+ return agent_problem(:llm_missing, agent_id: agent_id) if llm_model.blank?
+ return agent_problem(:llm_vision_disabled, agent_id: agent_id) if !llm_model.vision_enabled?
+
+ no_problem
+ end
+
+ private
+
+ def agent_problem(reason_key, agent_id:)
+ problem(
+ agent_id,
+ override_data: {
+ reason: I18n.t("dashboard.problem.ai_image_caption_agent_reasons.#{reason_key}"),
+ url: url(agent_id),
+ },
+ details: {
+ agent_id: agent_id,
+ reason: reason_key.to_s,
+ },
+ )
+ end
+
+ def url(agent_id)
+ if AiAgent.exists?(id: agent_id)
+ "#{Discourse.base_path}/admin/plugins/discourse-ai/ai-agents/#{agent_id}/edit"
+ else
+ "#{Discourse.base_path}/admin/plugins/discourse-ai/settings?filter=ai_image_caption_agent"
+ end
+ end
+end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-post-image-caption-editor-button.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-post-image-caption-editor-button.gjs
new file mode 100644
index 00000000000..f5f02f2b79e
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-post-image-caption-editor-button.gjs
@@ -0,0 +1,36 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import AiPostImageCaptionEditorModal from "./modal/ai-post-image-caption-editor";
+
+export default class AiPostImageCaptionEditorButton extends Component {
+ @service modal;
+ @service postImageCaptionEditor;
+
+ get caption() {
+ return this.postImageCaptionEditor.captionFor(this.args.base62Sha1);
+ }
+
+ @action
+ openEditor() {
+ this.modal.show(AiPostImageCaptionEditorModal, {
+ model: {
+ base62Sha1: this.args.base62Sha1,
+ description: this.caption,
+ },
+ });
+ }
+
+ <template>
+ {{#if this.caption}}
+ <DButton
+ @action={{this.openEditor}}
+ @ariaLabel="discourse_ai.post_image_captions.edit"
+ @icon="pencil"
+ @title="discourse_ai.post_image_captions.edit"
+ class="btn-transparent ai-post-image-caption-editor__button"
+ />
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-post-image-description-editor-button.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-post-image-description-editor-button.gjs
deleted file mode 100644
index 242ca175bae..00000000000
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-post-image-description-editor-button.gjs
+++ /dev/null
@@ -1,36 +0,0 @@
-import Component from "@glimmer/component";
-import { action } from "@ember/object";
-import { service } from "@ember/service";
-import DButton from "discourse/ui-kit/d-button";
-import AiPostImageDescriptionEditorModal from "./modal/ai-post-image-description-editor";
-
-export default class AiPostImageDescriptionEditorButton extends Component {
- @service modal;
- @service postImageDescriptionEditor;
-
- get description() {
- return this.postImageDescriptionEditor.descriptionFor(this.args.base62Sha1);
- }
-
- @action
- openEditor() {
- this.modal.show(AiPostImageDescriptionEditorModal, {
- model: {
- base62Sha1: this.args.base62Sha1,
- description: this.description,
- },
- });
- }
-
- <template>
- {{#if this.description}}
- <DButton
- @action={{this.openEditor}}
- @ariaLabel="discourse_ai.post_image_descriptions.edit"
- @icon="pencil"
- @title="discourse_ai.post_image_descriptions.edit"
- class="btn-transparent ai-post-image-description-editor__button"
- />
- {{/if}}
- </template>
-}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-post-image-description-editor.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-post-image-caption-editor.gjs
similarity index 70%
rename from plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-post-image-description-editor.gjs
rename to plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-post-image-caption-editor.gjs
index cf748b051f9..bd0ea6b41d5 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-post-image-description-editor.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-post-image-caption-editor.gjs
@@ -7,8 +7,8 @@ import DModal from "discourse/ui-kit/d-modal";
import DModalCancel from "discourse/ui-kit/d-modal-cancel";
import { i18n } from "discourse-i18n";
-export default class AiPostImageDescriptionEditorModal extends Component {
- @service postImageDescriptionEditor;
+export default class AiPostImageCaptionEditorModal extends Component {
+ @service postImageCaptionEditor;
@cached
get formData() {
@@ -20,7 +20,7 @@ export default class AiPostImageDescriptionEditorModal extends Component {
@action
async save(data) {
try {
- await this.postImageDescriptionEditor.save(
+ await this.postImageCaptionEditor.save(
this.args.model.base62Sha1,
data.description
);
@@ -33,27 +33,27 @@ export default class AiPostImageDescriptionEditorModal extends Component {
<template>
<DModal
@closeModal={{@closeModal}}
- @title={{i18n "discourse_ai.post_image_descriptions.title"}}
- class="ai-post-image-description-editor-modal"
+ @title={{i18n "discourse_ai.post_image_captions.title"}}
+ class="ai-post-image-caption-editor-modal"
>
<Form @data={{this.formData}} @onSubmit={{this.save}} as |form|>
<form.Field
@format="full"
@name="description"
- @title={{i18n "discourse_ai.post_image_descriptions.description"}}
+ @title={{i18n "discourse_ai.post_image_captions.description"}}
@type="textarea"
@validation="required:trim|length:1,1000"
as |field|
>
<field.Control
@height={{120}}
- class="ai-post-image-description-editor-modal__textarea"
+ class="ai-post-image-caption-editor-modal__textarea"
/>
</form.Field>
<form.Actions>
<DModalCancel @close={{@closeModal}} />
- <form.Submit @label="discourse_ai.post_image_descriptions.save" />
+ <form.Submit @label="discourse_ai.post_image_captions.save" />
</form.Actions>
</Form>
</DModal>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-post-image-description-editor.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-post-image-caption-editor.gjs
similarity index 58%
rename from plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-post-image-description-editor.gjs
rename to plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-post-image-caption-editor.gjs
index 412c90b61ea..937c6f7c2e8 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-post-image-description-editor.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-post-image-caption-editor.gjs
@@ -1,12 +1,12 @@
import { withPluginApi } from "discourse/lib/plugin-api";
-import AiPostImageDescriptionEditorButton from "../components/ai-post-image-description-editor-button";
+import AiPostImageCaptionEditorButton from "../components/ai-post-image-caption-editor-button";
import {
- ensureImageDescriptionTarget,
+ ensureImageCaptionTarget,
imageBase62Sha1,
-} from "../lib/post-image-description-editor";
+} from "../lib/post-image-caption-editor";
-function initializeAiPostImageDescriptionEditor(api) {
- const editor = api.container.lookup("service:post-image-description-editor");
+function initializeAiPostImageCaptionEditor(api) {
+ const editor = api.container.lookup("service:post-image-caption-editor");
api.decorateCookedElement(
(element, helper) => {
@@ -31,7 +31,7 @@ function initializeAiPostImageDescriptionEditor(api) {
return;
}
- const target = ensureImageDescriptionTarget(imageWrapper);
+ const target = ensureImageCaptionTarget(imageWrapper);
if (!target) {
return;
}
@@ -39,20 +39,20 @@ function initializeAiPostImageDescriptionEditor(api) {
helper.renderGlimmer(
target,
<template>
- <AiPostImageDescriptionEditorButton @base62Sha1={{base62Sha1}} />
+ <AiPostImageCaptionEditorButton @base62Sha1={{base62Sha1}} />
</template>
);
});
},
{
- id: "ai-post-image-description-editor",
+ id: "ai-post-image-caption-editor",
}
);
}
export default {
- name: "ai-post-image-description-editor",
+ name: "ai-post-image-caption-editor",
initialize() {
- withPluginApi(initializeAiPostImageDescriptionEditor);
+ withPluginApi(initializeAiPostImageCaptionEditor);
},
};
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js
index 4812bbd6d8e..e45b8b0ea2e 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js
@@ -23,10 +23,6 @@ export const AI_FEATURE_SETTING_GROUPS = {
settings: [
"ai_helper_automatic_chat_thread_title",
"ai_helper_automatic_chat_thread_title_delay",
- "ai_post_image_descriptions_enabled",
- "ai_post_image_descriptions_per_post_limit",
- "ai_post_image_descriptions_backfill_hourly_rate",
- "ai_post_image_descriptions_backfill_max_age_days",
],
},
{
@@ -41,12 +37,25 @@ export const AI_FEATURE_SETTING_GROUPS = {
"ai_helper_translator_agent",
"ai_helper_markdown_tables_agent",
"ai_helper_custom_prompt_agent",
- "ai_helper_image_caption_agent",
"ai_helper_chat_thread_title_agent",
],
},
],
+ image_caption: [
+ {
+ key: "settings",
+ titleKey: "discourse_ai.features.image_caption.setting_groups.settings",
+ settings: [
+ "ai_post_image_captions_enabled",
+ "ai_image_caption_agent",
+ "ai_post_image_captions_per_post_limit",
+ "ai_post_image_captions_backfill_hourly_rate",
+ "ai_post_image_captions_backfill_max_age_days",
+ ],
+ },
+ ],
+
embeddings: [
{
key: "model_settings",
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/post-image-description-editor.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/post-image-caption-editor.js
similarity index 91%
rename from plugins/discourse-ai/assets/javascripts/discourse/lib/post-image-description-editor.js
rename to plugins/discourse-ai/assets/javascripts/discourse/lib/post-image-caption-editor.js
index 090b490098e..832ead728f7 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/post-image-description-editor.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/post-image-caption-editor.js
@@ -71,16 +71,16 @@ function base62Encode(number) {
return encoded;
}
-export function ensureImageDescriptionTarget(imageWrapper) {
+export function ensureImageCaptionTarget(imageWrapper) {
const buttonWrapper = imageWrapper.querySelector(".button-wrapper");
if (!buttonWrapper) {
return;
}
- let target = buttonWrapper.querySelector(".ai-post-image-description-editor");
+ let target = buttonWrapper.querySelector(".ai-post-image-caption-editor");
if (!target) {
target = document.createElement("span");
- target.className = "ai-post-image-description-editor";
+ target.className = "ai-post-image-caption-editor";
buttonWrapper.appendChild(target);
}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/post-image-description-editor.js b/plugins/discourse-ai/assets/javascripts/discourse/services/post-image-caption-editor.js
similarity index 71%
rename from plugins/discourse-ai/assets/javascripts/discourse/services/post-image-description-editor.js
rename to plugins/discourse-ai/assets/javascripts/discourse/services/post-image-caption-editor.js
index 0d471c205fa..f8bf85b5acb 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/services/post-image-description-editor.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/post-image-caption-editor.js
@@ -5,19 +5,19 @@ import { popupAjaxError } from "discourse/lib/ajax-error";
import { EDIT } from "discourse/models/composer";
import { i18n } from "discourse-i18n";
-export default class PostImageDescriptionEditor extends Service {
+export default class PostImageCaptionEditor extends Service {
@service a11y;
@service composer;
@service siteSettings;
@service toasts;
- @tracked descriptions = new Map();
+ @tracked captions = new Map();
@tracked loadedKey = null;
@tracked loadingKey = null;
get canEditCurrentComposer() {
return Boolean(
- this.siteSettings.ai_post_image_descriptions_enabled &&
+ this.siteSettings.ai_post_image_captions_enabled &&
this.composer.model?.action === EDIT &&
this.currentPostId
);
@@ -39,12 +39,12 @@ export default class PostImageDescriptionEditor extends Service {
return `${this.currentPostId}:${this.currentLocale || ""}`;
}
- descriptionFor(base62Sha1) {
+ captionFor(base62Sha1) {
if (!this.canEditCurrentComposer || this.loadedKey !== this.currentKey) {
return;
}
- return this.descriptions.get(base62Sha1);
+ return this.captions.get(base62Sha1);
}
async ensureLoaded() {
@@ -60,28 +60,28 @@ export default class PostImageDescriptionEditor extends Service {
this.loadingKey = key;
this.loadedKey = null;
- this.descriptions = new Map();
+ this.captions = new Map();
try {
const result = await ajax(
- `/discourse-ai/post-image-descriptions/${this.currentPostId}`,
+ `/discourse-ai/post-image-captions/${this.currentPostId}`,
{
data: this.currentLocale ? { locale: this.currentLocale } : {},
}
);
if (this.currentKey === key) {
- this.descriptions = new Map(
- result.descriptions.map((description) => [
- description.base62_sha1,
- description.description,
+ this.captions = new Map(
+ result.captions.map((caption) => [
+ caption.base62_sha1,
+ caption.description,
])
);
this.loadedKey = key;
}
} catch {
if (this.currentKey === key) {
- this.descriptions = new Map();
+ this.captions = new Map();
this.loadedKey = key;
}
} finally {
@@ -94,7 +94,7 @@ export default class PostImageDescriptionEditor extends Service {
async save(base62Sha1, description) {
try {
const result = await ajax(
- `/discourse-ai/post-image-descriptions/${this.currentPostId}/${base62Sha1}`,
+ `/discourse-ai/post-image-captions/${this.currentPostId}/${base62Sha1}`,
{
type: "PUT",
data: {
@@ -104,12 +104,12 @@ export default class PostImageDescriptionEditor extends Service {
}
);
- const descriptions = new Map(this.descriptions);
- descriptions.set(result.base62_sha1, result.description);
- this.descriptions = descriptions;
+ const captions = new Map(this.captions);
+ captions.set(result.base62_sha1, result.description);
+ this.captions = captions;
this.loadedKey = this.currentKey;
- const message = i18n("discourse_ai.post_image_descriptions.saved");
+ const message = i18n("discourse_ai.post_image_captions.saved");
this.toasts.success({
duration: "short",
data: { message },
@@ -124,7 +124,7 @@ export default class PostImageDescriptionEditor extends Service {
}
#reset() {
- this.descriptions = new Map();
+ this.captions = new Map();
this.loadedKey = null;
this.loadingKey = null;
}
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss
index 4ebc10185a0..4ea9552bebf 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss
@@ -468,7 +468,7 @@
}
}
-.ai-post-image-description-editor {
+.ai-post-image-caption-editor {
display: contents;
&__button.btn-transparent {
@@ -478,7 +478,7 @@
}
}
-.ai-post-image-description-editor-modal {
+.ai-post-image-caption-editor-modal {
&__textarea {
min-height: 7em;
}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 2890d20866a..5b17c8ac570 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -232,12 +232,12 @@ en:
discourse_ai:
title: "AI"
- post_image_descriptions:
- edit: "Edit AI image description"
- title: "Edit AI image description"
- description: "Description"
- save: "Save description"
- saved: "AI image description saved"
+ post_image_captions:
+ edit: "Edit AI image caption"
+ title: "Edit AI image caption"
+ description: "Caption"
+ save: "Save caption"
+ saved: "AI image caption saved"
discourse_workflows:
ai_agent:
agent_id: "Agent"
@@ -386,6 +386,13 @@ en:
automation: "Automation"
agents: "Agents"
+ image_caption:
+ name: "Image Caption"
+ description: "Generates AI captions for post images and makes them available to readers and assistive technology"
+ post_image_captions: "Post image captions"
+ setting_groups:
+ settings: "Settings"
+
translation:
name: "Translation"
description: "Translates content into supported languages"
@@ -964,7 +971,7 @@ en:
usage:
ai_bot: "AI bot"
ai_helper: "Helper (%{agent})"
- ai_helper_image_caption: "Image caption"
+ ai_image_caption: "Image caption"
ai_agent: "Agent (%{agent})"
ai_summarization: "Summarize"
ai_embeddings_semantic_search: "AI search"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index dd0a4f18b26..daaeb8a6cac 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -11,6 +11,12 @@ en:
other: "<a href='%{base_path}/admin/plugins/discourse-ai/ai-llms/%{target}/edit'>%{model_name}</a> needs attention. Over the last %{count} hours, it failed to respond %{failed_calls} out of %{total_calls} times."
ai_credit_soft_limit: "%{model_name} has only %{percentage_remaining}% of credits remaining. Credits will reset at %{reset_date}. <a href='%{url}'>View AI models</a>"
ai_credit_hard_limit: "You have run out of AI credits for %{model_name}. AI features will be unavailable until %{reset_date}. <a href='%{url}'>View AI models</a>"
+ ai_image_caption_agent: "AI image captions are enabled, but the selected image caption agent is not ready: %{reason}. <a href='%{url}'>Review the image caption agent</a>."
+ ai_image_caption_agent_reasons:
+ agent_missing: "the selected agent does not exist"
+ agent_vision_disabled: "the agent cannot include image uploads"
+ llm_missing: "the agent does not resolve to an LLM"
+ llm_vision_disabled: "the resolved LLM does not support image input"
discourse_automation:
ai:
flag_types:
@@ -103,10 +109,11 @@ en:
ai_helper_automatic_chat_thread_title_delay: "Delay in minutes before the AI helper automatically sets the chat thread title."
ai_helper_automatic_chat_thread_title: "Automatically set the chat thread titles based on thread contents."
ai_helper_enabled_features: "Select the features to enable in the AI helper."
- ai_post_image_descriptions_enabled: "Enable AI image descriptions for post images. Generating missing descriptions requires a vision-capable image caption agent."
- ai_post_image_descriptions_per_post_limit: "Maximum number of post images to describe per post."
- ai_post_image_descriptions_backfill_hourly_rate: "Maximum number of posts per hour to backfill with AI-generated image descriptions. Set to 0 to disable backfill."
- ai_post_image_descriptions_backfill_max_age_days: "Maximum age in days of posts to backfill with AI-generated image descriptions."
+ ai_image_caption_agent: "The agent to use for AI image captions. Custom agents must have image uploads enabled and use a vision-capable LLM."
+ ai_post_image_captions_enabled: "Enable AI captions for post images. Generating missing captions requires a configured {{setting:ai_image_caption_agent}}."
+ ai_post_image_captions_per_post_limit: "Maximum number of post images to caption per post."
+ ai_post_image_captions_backfill_hourly_rate: "Maximum number of posts per hour to backfill with AI-generated image captions. Set to 0 to disable backfill."
+ ai_post_image_captions_backfill_max_age_days: "Maximum age in days of posts to backfill with AI-generated image captions."
post_ai_helper_allowed_groups: "User groups allowed to access AI Helper features in posts"
ai_helper_post_illustrator_agent: "The agent to use for the AI helper's illustrate post feature. Note: you must also create an image generation tool (Admin > Plugins > Discourse AI > Tools) for this feature to work."
ai_helper_chat_thread_title_agent: "The agent to use for generating chat thread titles."
@@ -383,12 +390,18 @@ en:
replace_dates: "Smart dates"
image_caption:
aria_description: "%{description} (Captioned by AI)"
- post_image_descriptions:
+ image_caption:
+ configuration:
+ agent_missing: "Select an existing agent for AI image captions."
+ agent_vision_disabled: "The AI image caption agent must have image uploads enabled."
+ llm_missing: "The AI image caption agent must use an LLM."
+ llm_vision_disabled: "The AI image caption agent must use a vision-capable LLM."
+ post_image_captions:
errors:
- description_blank: "Description can't be blank."
+ description_blank: "Caption can't be blank."
description_too_long:
- one: "Description must be %{count} character or fewer."
- other: "Description must be %{count} characters or fewer."
+ one: "Caption must be %{count} character or fewer."
+ other: "Caption must be %{count} characters or fewer."
share_ai:
read_more: "Read full transcript"
@@ -507,7 +520,7 @@ en:
description: "Default agent powering the Helper's translator feature"
image_captioner:
name: "Image captions"
- description: "Default agent powering the Helper's image caption feature"
+ description: "Default agent powering the image caption feature"
locale_detector:
name: "Locale detector"
description: "Powers the translation feature by detecting the locale of a given text (posts, titles, etc.)"
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index 67d8b23ea16..a615b946170 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -5,9 +5,9 @@ DiscourseAi::Engine.routes.draw do
get "status" => "ai_credits#status"
end
- scope path: "/post-image-descriptions", defaults: { format: :json } do
- get ":post_id" => "post_image_descriptions#index"
- put ":post_id/:base62_sha1" => "post_image_descriptions#update"
+ scope path: "/post-image-captions", defaults: { format: :json } do
+ get ":post_id" => "post_image_captions#index"
+ put ":post_id/:base62_sha1" => "post_image_captions#update"
end
scope module: :ai_helper, path: "/ai-helper", defaults: { format: :json } do
diff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.yml
index 0ed406065dd..93875bd7c88 100644
--- a/plugins/discourse-ai/config/settings.yml
+++ b/plugins/discourse-ai/config/settings.yml
@@ -181,28 +181,30 @@ discourse_ai:
type: enum
enum: "DiscourseAi::Configuration::AgentEnumerator"
area: "ai-features/ai_helper"
- ai_helper_image_caption_agent:
+ ai_image_caption_agent:
default: "-26"
type: enum
enum: "DiscourseAi::Configuration::AgentEnumerator"
- area: "ai-features/ai_helper"
- ai_post_image_descriptions_enabled:
+ validator: "DiscourseAi::Configuration::ImageCaptionAgentValidator"
+ area: "ai-features/image_caption"
+ ai_post_image_captions_enabled:
default: false
client: true
- area: "ai-features/ai_helper"
- ai_post_image_descriptions_per_post_limit:
+ validator: "DiscourseAi::Configuration::ImageCaptionEnabledValidator"
+ area: "ai-features/image_caption"
+ ai_post_image_captions_per_post_limit:
default: 10
min: 1
- area: "ai-features/ai_helper"
- ai_post_image_descriptions_backfill_hourly_rate:
+ area: "ai-features/image_caption"
+ ai_post_image_captions_backfill_hourly_rate:
default: 0
min: 0
- area: "ai-features/ai_helper"
- ai_post_image_descriptions_backfill_max_age_days:
+ area: "ai-features/image_caption"
+ ai_post_image_captions_backfill_max_age_days:
default: 30
min: 1
max: 10000
- area: "ai-features/ai_helper"
+ area: "ai-features/image_caption"
ai_helper_chat_thread_title_agent:
default: "-35"
type: enum
diff --git a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
index 314421c7033..19dba5138ab 100644
--- a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
+++ b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
@@ -107,6 +107,9 @@ DiscourseAi::Agents::Agent.system_agents.each do |agent_class, id|
agent.system_prompt = instance.system_prompt
agent.top_p = instance.top_p
agent.temperature = instance.temperature
+ if agent_class == DiscourseAi::Agents::ImageCaptioner
+ agent.vision_enabled = agent_class.vision_enabled
+ end
# Only seed the shipped default when the admin has never set one, so we don't
# clobber a per-agent choice on every deploy (thinking_effort is DB-driven and
# editable in the UI, unlike temperature/top_p which are code-owned).
diff --git a/plugins/discourse-ai/db/migrate/20260706151932_create_ai_post_image_descriptions.rb b/plugins/discourse-ai/db/migrate/20260706151932_create_ai_post_image_captions.rb
similarity index 61%
rename from plugins/discourse-ai/db/migrate/20260706151932_create_ai_post_image_descriptions.rb
rename to plugins/discourse-ai/db/migrate/20260706151932_create_ai_post_image_captions.rb
index f00a80e026e..c5464a83ca3 100644
--- a/plugins/discourse-ai/db/migrate/20260706151932_create_ai_post_image_descriptions.rb
+++ b/plugins/discourse-ai/db/migrate/20260706151932_create_ai_post_image_captions.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
-class CreateAiPostImageDescriptions < ActiveRecord::Migration[8.0]
+class CreateAiPostImageCaptions < ActiveRecord::Migration[8.0]
def change
- create_table :ai_post_image_descriptions do |t|
+ create_table :ai_post_image_captions do |t|
t.integer :post_id, null: false
t.integer :upload_id, null: false
t.string :base62_sha1, null: false, limit: 27
@@ -14,12 +14,12 @@ class CreateAiPostImageDescriptions < ActiveRecord::Migration[8.0]
t.timestamps null: false
end
- add_index :ai_post_image_descriptions,
+ add_index :ai_post_image_captions,
%i[post_id locale base62_sha1],
unique: true,
- name: "idx_ai_post_image_descriptions_lookup"
- add_index :ai_post_image_descriptions,
+ name: "idx_ai_post_image_captions_lookup"
+ add_index :ai_post_image_captions,
%i[base62_sha1 locale],
- name: "idx_ai_post_image_descriptions_reuse"
+ name: "idx_ai_post_image_captions_reuse"
end
end
diff --git a/plugins/discourse-ai/db/migrate/20260715064155_rename_ai_image_caption_site_settings.rb b/plugins/discourse-ai/db/migrate/20260715064155_rename_ai_image_caption_site_settings.rb
new file mode 100644
index 00000000000..7cbf29d6c78
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260715064155_rename_ai_image_caption_site_settings.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+class RenameAiImageCaptionSiteSettings < ActiveRecord::Migration[8.0]
+ def up
+ rename_setting("ai_helper_image_caption_agent", "ai_image_caption_agent")
+ rename_setting("ai_post_image_descriptions_enabled", "ai_post_image_captions_enabled")
+ rename_setting(
+ "ai_post_image_descriptions_per_post_limit",
+ "ai_post_image_captions_per_post_limit",
+ )
+ rename_setting(
+ "ai_post_image_descriptions_backfill_hourly_rate",
+ "ai_post_image_captions_backfill_hourly_rate",
+ )
+ rename_setting(
+ "ai_post_image_descriptions_backfill_max_age_days",
+ "ai_post_image_captions_backfill_max_age_days",
+ )
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+
+ private
+
+ def rename_setting(old_name, new_name)
+ old_name = connection.quote(old_name)
+ new_name = connection.quote(new_name)
+
+ execute <<~SQL
+ DELETE FROM site_settings old_settings
+ WHERE old_settings.name = #{old_name}
+ AND EXISTS (
+ SELECT 1
+ FROM site_settings new_settings
+ WHERE new_settings.name = #{new_name}
+ )
+ SQL
+
+ execute <<~SQL
+ UPDATE site_settings
+ SET name = #{new_name}
+ WHERE name = #{old_name}
+ SQL
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20260715090355_copy_ai_post_image_descriptions_to_captions.rb b/plugins/discourse-ai/db/migrate/20260715090355_copy_ai_post_image_descriptions_to_captions.rb
new file mode 100644
index 00000000000..407a2cab947
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260715090355_copy_ai_post_image_descriptions_to_captions.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+class CopyAiPostImageDescriptionsToCaptions < ActiveRecord::Migration[8.0]
+ def up
+ execute <<~SQL
+ CREATE TABLE IF NOT EXISTS ai_post_image_captions (
+ id bigserial PRIMARY KEY,
+ post_id integer NOT NULL,
+ upload_id integer NOT NULL,
+ base62_sha1 varchar(27) NOT NULL,
+ locale varchar(20) NOT NULL,
+ description text,
+ attempts integer DEFAULT 0 NOT NULL,
+ last_attempted_at timestamp(6) without time zone,
+ last_error text,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+ )
+ SQL
+
+ execute <<~SQL
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_ai_post_image_captions_lookup
+ ON ai_post_image_captions (post_id, locale, base62_sha1)
+ SQL
+
+ execute <<~SQL
+ CREATE INDEX IF NOT EXISTS idx_ai_post_image_captions_reuse
+ ON ai_post_image_captions (base62_sha1, locale)
+ SQL
+
+ return if !table_exists?(:ai_post_image_descriptions)
+
+ execute <<~SQL
+ INSERT INTO ai_post_image_captions (
+ post_id,
+ upload_id,
+ base62_sha1,
+ locale,
+ description,
+ attempts,
+ last_attempted_at,
+ last_error,
+ created_at,
+ updated_at
+ )
+ SELECT
+ post_id,
+ upload_id,
+ base62_sha1,
+ locale,
+ description,
+ attempts,
+ last_attempted_at,
+ last_error,
+ created_at,
+ updated_at
+ FROM ai_post_image_descriptions
+ ON CONFLICT (post_id, locale, base62_sha1) DO NOTHING
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/db/post_migrate/20260306000002_finalize_ai_agents_schema.rb b/plugins/discourse-ai/db/post_migrate/20260306000002_finalize_ai_agents_schema.rb
index ad22be9d9c7..e48893d872b 100644
--- a/plugins/discourse-ai/db/post_migrate/20260306000002_finalize_ai_agents_schema.rb
+++ b/plugins/discourse-ai/db/post_migrate/20260306000002_finalize_ai_agents_schema.rb
@@ -12,7 +12,7 @@ class FinalizeAiAgentsSchema < ActiveRecord::Migration[7.2]
"ai_helper_translator_persona" => "ai_helper_translator_agent",
"ai_helper_markdown_tables_persona" => "ai_helper_markdown_tables_agent",
"ai_helper_custom_prompt_persona" => "ai_helper_custom_prompt_agent",
- "ai_helper_image_caption_persona" => "ai_helper_image_caption_agent",
+ "ai_helper_image_caption_persona" => "ai_image_caption_agent",
"ai_helper_chat_thread_title_persona" => "ai_helper_chat_thread_title_agent",
"ai_embeddings_semantic_search_hyde_persona" => "ai_embeddings_semantic_search_hyde_agent",
"ai_summarization_persona" => "ai_summarization_agent",
diff --git a/plugins/discourse-ai/db/post_migrate/20260715090434_drop_ai_post_image_descriptions.rb b/plugins/discourse-ai/db/post_migrate/20260715090434_drop_ai_post_image_descriptions.rb
new file mode 100644
index 00000000000..1d675ae8f73
--- /dev/null
+++ b/plugins/discourse-ai/db/post_migrate/20260715090434_drop_ai_post_image_descriptions.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class DropAiPostImageDescriptions < ActiveRecord::Migration[8.0]
+ def up
+ execute "DROP TABLE IF EXISTS ai_post_image_descriptions"
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/image_captioner.rb b/plugins/discourse-ai/lib/agents/image_captioner.rb
index 7f94798dce9..40cb3c27ff0 100644
--- a/plugins/discourse-ai/lib/agents/image_captioner.rb
+++ b/plugins/discourse-ai/lib/agents/image_captioner.rb
@@ -7,6 +7,10 @@ module DiscourseAi
false
end
+ def self.vision_enabled
+ true
+ end
+
def system_prompt
<<~PROMPT.strip
You are a bot specializing in image captioning.
diff --git a/plugins/discourse-ai/lib/ai_helper/assistant.rb b/plugins/discourse-ai/lib/ai_helper/assistant.rb
index 0703538e59d..dbd1df8234b 100644
--- a/plugins/discourse-ai/lib/ai_helper/assistant.rb
+++ b/plugins/discourse-ai/lib/ai_helper/assistant.rb
@@ -381,7 +381,7 @@ module DiscourseAi
}
if include_image_caption
- image_caption_agent = SiteSetting.ai_helper_image_caption_agent.to_i
+ image_caption_agent = SiteSetting.ai_image_caption_agent.to_i
map[image_caption_agent] = IMAGE_CAPTION if image_caption_agent
end
diff --git a/plugins/discourse-ai/lib/configuration/feature.rb b/plugins/discourse-ai/lib/configuration/feature.rb
index c38c4498989..9cab9eefc54 100644
--- a/plugins/discourse-ai/lib/configuration/feature.rb
+++ b/plugins/discourse-ai/lib/configuration/feature.rb
@@ -144,6 +144,17 @@ module DiscourseAi
]
end
+ def image_caption_features
+ feature_cache[:image_caption] ||= [
+ new(
+ "post_image_captions",
+ "ai_image_caption_agent",
+ DiscourseAi::Configuration::Module::IMAGE_CAPTION_ID,
+ DiscourseAi::Configuration::Module::IMAGE_CAPTION,
+ ),
+ ]
+ end
+
def spam_features
feature_cache[:spam] ||= [
new(
@@ -184,6 +195,7 @@ module DiscourseAi
def lookup_bot_agent_ids
AiAgent
.where(enabled: true)
+ .where.not(id: SiteSetting.ai_image_caption_agent.to_i)
.where(
"allow_chat_channel_mentions OR allow_chat_direct_messages OR allow_topic_mentions OR allow_personal_messages",
)
@@ -320,6 +332,7 @@ module DiscourseAi
discord_features,
inference_features,
ai_helper_features,
+ image_caption_features,
translation_features,
bot_features,
spam_features,
@@ -387,6 +400,8 @@ module DiscourseAi
DiscourseAi::Summarization.find_summarization_model(agent_klass)
when DiscourseAi::Configuration::Module::AI_HELPER
DiscourseAi::AiHelper::Assistant.find_ai_helper_model(name, agent_klass)
+ when DiscourseAi::Configuration::Module::IMAGE_CAPTION
+ DiscourseAi::PostImageCaptions.image_caption_llm_model(agent)
when DiscourseAi::Configuration::Module::TRANSLATION
DiscourseAi::Translation::BaseTranslator.preferred_llm_model(agent_klass)
when DiscourseAi::Configuration::Module::EMBEDDINGS
diff --git a/plugins/discourse-ai/lib/configuration/image_caption_agent_validator.rb b/plugins/discourse-ai/lib/configuration/image_caption_agent_validator.rb
new file mode 100644
index 00000000000..792a866f8d4
--- /dev/null
+++ b/plugins/discourse-ai/lib/configuration/image_caption_agent_validator.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Configuration
+ class ImageCaptionAgentValidator
+ DEFAULT_AGENT_ID = "-26"
+
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(val)
+ return true if val.to_s == DEFAULT_AGENT_ID
+
+ valid_agent_value?(val)
+ end
+
+ def valid_agent_value?(val)
+ agent = AiAgent.find_by(id: val.to_i)
+ return invalid(:agent_missing) if agent.blank?
+
+ agent_class = agent.class_instance
+ return invalid(:agent_vision_disabled) if !agent_class&.vision_enabled
+
+ llm_model =
+ DiscourseAi::AiHelper::Assistant.find_ai_helper_model(
+ DiscourseAi::AiHelper::Assistant::IMAGE_CAPTION,
+ agent_class,
+ )
+ return invalid(:llm_missing) if llm_model.blank?
+ return invalid(:llm_vision_disabled) if !llm_model.vision_enabled?
+
+ true
+ end
+
+ def error_message
+ I18n.t("discourse_ai.image_caption.configuration.#{@error_key}")
+ end
+
+ private
+
+ def invalid(error_key)
+ @error_key = error_key
+ false
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/configuration/image_caption_enabled_validator.rb b/plugins/discourse-ai/lib/configuration/image_caption_enabled_validator.rb
new file mode 100644
index 00000000000..2dcde6ef2e7
--- /dev/null
+++ b/plugins/discourse-ai/lib/configuration/image_caption_enabled_validator.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Configuration
+ class ImageCaptionEnabledValidator
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(val)
+ return true if val == false || val == "f" || val == "false"
+
+ agent_validator.valid_agent_value?(SiteSetting.ai_image_caption_agent)
+ end
+
+ def error_message
+ agent_validator.error_message
+ end
+
+ private
+
+ def agent_validator
+ @agent_validator ||= ImageCaptionAgentValidator.new(@opts)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/configuration/llm_enumerator.rb b/plugins/discourse-ai/lib/configuration/llm_enumerator.rb
index 314178179f7..b1f8a3d147a 100644
--- a/plugins/discourse-ai/lib/configuration/llm_enumerator.rb
+++ b/plugins/discourse-ai/lib/configuration/llm_enumerator.rb
@@ -47,13 +47,13 @@ module DiscourseAi
end
end
- if SiteSetting.ai_post_image_descriptions_enabled
- image_caption_agent = AiAgent.find_by(id: SiteSetting.ai_helper_image_caption_agent)
+ if SiteSetting.ai_post_image_captions_enabled
+ image_caption_agent = AiAgent.find_by(id: SiteSetting.ai_image_caption_agent)
if image_caption_agent.present?
model_id = image_caption_agent.default_llm_id || SiteSetting.ai_default_llm_model.to_i
- rval[model_id] << { type: :ai_helper_image_caption }
+ rval[model_id] << { type: :ai_image_caption }
end
end
diff --git a/plugins/discourse-ai/lib/configuration/module.rb b/plugins/discourse-ai/lib/configuration/module.rb
index 8d1b1168d5c..2842b4c6a56 100644
--- a/plugins/discourse-ai/lib/configuration/module.rb
+++ b/plugins/discourse-ai/lib/configuration/module.rb
@@ -8,6 +8,7 @@ module DiscourseAi
DISCORD = "discord"
INFERENCE = "inference"
AI_HELPER = "ai_helper"
+ IMAGE_CAPTION = "image_caption"
TRANSLATION = "translation"
BOT = "bot"
SPAM = "spam"
@@ -22,6 +23,7 @@ module DiscourseAi
DISCORD,
INFERENCE,
AI_HELPER,
+ IMAGE_CAPTION,
TRANSLATION,
BOT,
SPAM,
@@ -43,6 +45,7 @@ module DiscourseAi
AUTOMATION_REPORTS_ID = 10
AUTOMATION_TRIAGE_ID = 11
ADMIN_DASHBOARD_ID = 12
+ IMAGE_CAPTION_ID = 13
class << self
def external_module_id(module_name)
@@ -81,6 +84,12 @@ module DiscourseAi
enabled_by_setting: "ai_helper_enabled",
features: DiscourseAi::Configuration::Feature.ai_helper_features,
),
+ new(
+ IMAGE_CAPTION_ID,
+ IMAGE_CAPTION,
+ enabled_by_setting: "ai_post_image_captions_enabled",
+ features: DiscourseAi::Configuration::Feature.image_caption_features,
+ ),
new(
TRANSLATION_ID,
TRANSLATION,
diff --git a/plugins/discourse-ai/lib/post_image_descriptions.rb b/plugins/discourse-ai/lib/post_image_captions.rb
similarity index 79%
rename from plugins/discourse-ai/lib/post_image_descriptions.rb
rename to plugins/discourse-ai/lib/post_image_captions.rb
index 306cae5e7a8..3ff39c8ccdf 100644
--- a/plugins/discourse-ai/lib/post_image_descriptions.rb
+++ b/plugins/discourse-ai/lib/post_image_captions.rb
@@ -1,31 +1,33 @@
# frozen_string_literal: true
module DiscourseAi
- module PostImageDescriptions
- DESCRIPTION_CLASS = "ai-image-description"
- DESCRIPTION_ID_PREFIX = "ai-image-description"
+ module PostImageCaptions
+ CAPTION_CLASS = "ai-image-caption"
+ CAPTION_ID_PREFIX = "ai-image-caption"
+ LEGACY_DESCRIPTION_CLASS = "ai-image-description"
+ LEGACY_DESCRIPTION_ID_PREFIX = "ai-image-description"
ARIA_DESCRIPTION_ATTRIBUTE = "aria-description"
- LOOKUP_INDEX = "idx_ai_post_image_descriptions_lookup"
- REUSE_INDEX = "idx_ai_post_image_descriptions_reuse"
+ LOOKUP_INDEX = "idx_ai_post_image_captions_lookup"
+ REUSE_INDEX = "idx_ai_post_image_captions_reuse"
MAX_ATTEMPTS = 3
RETRY_AFTER = 1.day
COOK_ENQUEUE_POST_MAX_AGE = 1.day
BACKFILL_RUNS_PER_HOUR = 4
SUPPORTED_EXTENSIONS = %w[jpg jpeg png gif webp].freeze
- MAX_DESCRIPTION_LENGTH = 1_000
+ MAX_CAPTION_LENGTH = 1_000
module_function
def enabled?
- SiteSetting.discourse_ai_enabled && SiteSetting.ai_post_image_descriptions_enabled &&
- SiteSetting.ai_helper_image_caption_agent.present?
+ SiteSetting.discourse_ai_enabled && SiteSetting.ai_post_image_captions_enabled &&
+ SiteSetting.ai_image_caption_agent.present?
end
def generation_enabled?
return false if !enabled?
agent = image_caption_agent
- return false if agent.blank? || !agent.enabled?
+ return false if agent.blank?
llm_model = image_caption_llm_model(agent)
@@ -33,35 +35,35 @@ module DiscourseAi
end
def process_cooked(doc, post, locale:)
- remove_existing_description_metadata(doc)
+ remove_existing_caption_metadata(doc)
return if !enabled?
return if !captionable_post?(post)
base62_sha1s = image_base62_sha1s(doc, post_id: post.id)
base62_sha1s = capped_base62_sha1s(base62_sha1s)
- delete_removed_descriptions(post, locale, base62_sha1s)
+ delete_removed_captions(post, locale, base62_sha1s)
return if base62_sha1s.blank?
- descriptions = descriptions_for(post.id, locale, base62_sha1s)
- exact_description_base62_sha1s = descriptions.keys
- descriptions = descriptions_with_locale_fallback(post, locale, base62_sha1s, descriptions)
- decorate(doc, descriptions:, locale:)
+ captions = captions_for(post.id, locale, base62_sha1s)
+ exact_caption_base62_sha1s = captions.keys
+ captions = captions_with_locale_fallback(post, locale, base62_sha1s, captions)
+ decorate(doc, captions:, locale:)
enqueue_missing(
post,
locale: locale,
base62_sha1s: base62_sha1s,
- existing_base62_sha1s: exact_description_base62_sha1s,
+ existing_base62_sha1s: exact_caption_base62_sha1s,
)
end
- def decorate(doc, descriptions:, locale:)
- return if descriptions.blank?
+ def decorate(doc, captions:, locale:)
+ return if captions.blank?
image_nodes(doc).each do |img|
base62_sha1 = image_node_base62_sha1(img)
- description = descriptions[base62_sha1]
+ description = captions[base62_sha1]
next if description.blank?
aria_description = aria_description(description, locale)
@@ -79,7 +81,7 @@ module DiscourseAi
return if missing_base62_sha1s.blank?
Jobs.enqueue(
- :generate_post_image_descriptions,
+ :generate_post_image_captions,
post_id: post.id,
locale: locale,
base62_sha1s: missing_base62_sha1s,
@@ -105,8 +107,7 @@ module DiscourseAi
uploads_by_base62_sha1 = uploads_by_base62_sha1(missing_base62_sha1s)
- generated_count =
- reuse_descriptions(post, locale, missing_base62_sha1s, uploads_by_base62_sha1)
+ generated_count = reuse_captions(post, locale, missing_base62_sha1s, uploads_by_base62_sha1)
missing_base62_sha1s = pending_base62_sha1s(post.id, locale, current_base62_sha1s)
return 0 if generated_count == 0 && missing_base62_sha1s.blank?
@@ -160,19 +161,19 @@ module DiscourseAi
base62_sha1s = capped_base62_sha1s(base62_sha1s)
return text if base62_sha1s.blank?
- descriptions =
- AiPostImageDescription
+ captions =
+ AiPostImageCaption
.where(post_id: post_id, locale: locale, base62_sha1: base62_sha1s)
.where.not(description: nil)
.distinct
.pluck(:description)
- return text if descriptions.blank?
+ return text if captions.blank?
- "#{text} #{descriptions.join(" ")}"
+ "#{text} #{captions.join(" ")}"
end
- def editable_descriptions(post, locale)
+ def editable_captions(post, locale)
return [] if !enabled?
return [] if !captionable_post?(post)
@@ -180,44 +181,44 @@ module DiscourseAi
base62_sha1s = current_base62_sha1s(post)
return [] if base62_sha1s.blank?
- descriptions = descriptions_for(post.id, locale, base62_sha1s)
+ captions = captions_for(post.id, locale, base62_sha1s)
base62_sha1s.filter_map do |base62_sha1|
- description = descriptions[base62_sha1]
+ description = captions[base62_sha1]
next if description.blank?
{ base62_sha1: base62_sha1, description: description }
end
end
- def update_description(post, locale, base62_sha1, description)
+ def update_caption(post, locale, base62_sha1, description)
return if !enabled?
return if !captionable_post?(post)
return if !current_base62_sha1s(post).include?(base62_sha1)
locale = locale.presence || original_locale(post)
- image_description =
- AiPostImageDescription.find_by(post_id: post.id, locale: locale, base62_sha1: base62_sha1)
+ image_caption =
+ AiPostImageCaption.find_by(post_id: post.id, locale: locale, base62_sha1: base62_sha1)
- return if image_description.blank? || image_description.description.blank?
+ return if image_caption.blank? || image_caption.description.blank?
- image_description.update!(description: description, last_error: nil)
+ image_caption.update!(description: description, last_error: nil)
SearchIndexer.index(post, force: true)
refresh_cooked(post, locale)
- image_description
+ image_caption
end
def backfill_limit
- hourly_rate = SiteSetting.ai_post_image_descriptions_backfill_hourly_rate.to_i
+ hourly_rate = SiteSetting.ai_post_image_captions_backfill_hourly_rate.to_i
return 0 if hourly_rate <= 0
used_budget = DB.query_single(<<~SQL, threshold: 1.hour.ago).first.to_i
SELECT COUNT(*)
FROM (
SELECT DISTINCT post_id, locale
- FROM ai_post_image_descriptions
+ FROM ai_post_image_captions
WHERE created_at > :threshold OR last_attempted_at > :threshold
) recent_targets
SQL
@@ -234,7 +235,7 @@ module DiscourseAi
connection = ActiveRecord::Base.connection
default_locale = connection.quote(SiteSetting.default_locale)
retry_after = connection.quote(RETRY_AFTER.ago)
- max_age_days = SiteSetting.ai_post_image_descriptions_backfill_max_age_days.to_i
+ max_age_days = SiteSetting.ai_post_image_captions_backfill_max_age_days.to_i
original_locale_sql = "COALESCE(NULLIF(posts.locale, ''), #{default_locale})"
supported_extensions =
SUPPORTED_EXTENSIONS.map { |extension| connection.quote(extension) }.join(", ")
@@ -284,26 +285,26 @@ module DiscourseAi
SELECT candidate_targets.post_id,
candidate_targets.locale
FROM candidate_targets
- LEFT JOIN ai_post_image_descriptions existing_descriptions
- ON existing_descriptions.post_id = candidate_targets.post_id
- AND existing_descriptions.upload_id = candidate_targets.upload_id
- AND existing_descriptions.locale = candidate_targets.locale
+ LEFT JOIN ai_post_image_captions existing_captions
+ ON existing_captions.post_id = candidate_targets.post_id
+ AND existing_captions.upload_id = candidate_targets.upload_id
+ AND existing_captions.locale = candidate_targets.locale
AND (
- existing_descriptions.description IS NOT NULL OR
- existing_descriptions.attempts >= #{MAX_ATTEMPTS} OR
- existing_descriptions.last_attempted_at > #{retry_after}
+ existing_captions.description IS NOT NULL OR
+ existing_captions.attempts >= #{MAX_ATTEMPTS} OR
+ existing_captions.last_attempted_at > #{retry_after}
)
- WHERE existing_descriptions.post_id IS NULL
+ WHERE existing_captions.post_id IS NULL
OR EXISTS (
SELECT 1
- FROM ai_post_image_descriptions retryable_descriptions
- WHERE retryable_descriptions.post_id = candidate_targets.post_id
- AND retryable_descriptions.locale = candidate_targets.locale
- AND retryable_descriptions.description IS NULL
- AND retryable_descriptions.attempts < #{MAX_ATTEMPTS}
+ FROM ai_post_image_captions retryable_captions
+ WHERE retryable_captions.post_id = candidate_targets.post_id
+ AND retryable_captions.locale = candidate_targets.locale
+ AND retryable_captions.description IS NULL
+ AND retryable_captions.attempts < #{MAX_ATTEMPTS}
AND (
- retryable_descriptions.last_attempted_at IS NULL OR
- retryable_descriptions.last_attempted_at <= #{retry_after}
+ retryable_captions.last_attempted_at IS NULL OR
+ retryable_captions.last_attempted_at <= #{retry_after}
)
)
GROUP BY candidate_targets.post_id, candidate_targets.locale
@@ -352,25 +353,25 @@ module DiscourseAi
sha1s_by_base62_sha1.keys
end
- def descriptions_for(post_id, locale, base62_sha1s)
- AiPostImageDescription
+ def captions_for(post_id, locale, base62_sha1s)
+ AiPostImageCaption
.where(post_id: post_id, locale: locale, base62_sha1: base62_sha1s)
.where.not(description: nil)
.pluck(:base62_sha1, :description)
.to_h
end
- def descriptions_with_locale_fallback(post, locale, base62_sha1s, descriptions)
- return descriptions if locale == original_locale(post)
+ def captions_with_locale_fallback(post, locale, base62_sha1s, captions)
+ return captions if locale == original_locale(post)
- missing_base62_sha1s = base62_sha1s - descriptions.keys
- return descriptions if missing_base62_sha1s.blank?
+ missing_base62_sha1s = base62_sha1s - captions.keys
+ return captions if missing_base62_sha1s.blank?
- descriptions_for(post.id, original_locale(post), missing_base62_sha1s).merge(descriptions)
+ captions_for(post.id, original_locale(post), missing_base62_sha1s).merge(captions)
end
def capped_base62_sha1s(base62_sha1s)
- base62_sha1s.first(SiteSetting.ai_post_image_descriptions_per_post_limit.to_i)
+ base62_sha1s.first(SiteSetting.ai_post_image_captions_per_post_limit.to_i)
end
def current_base62_sha1s(post)
@@ -382,7 +383,7 @@ module DiscourseAi
def pending_base62_sha1s(post_id, locale, base62_sha1s)
rows =
- AiPostImageDescription
+ AiPostImageCaption
.where(post_id: post_id, locale: locale, base62_sha1: base62_sha1s)
.pluck(:base62_sha1, :description, :attempts, :last_attempted_at)
.index_by(&:first)
@@ -413,28 +414,28 @@ module DiscourseAi
sha1s_by_base62_sha1.transform_values { |sha1| uploads_by_sha1[sha1] }.compact
end
- def reuse_descriptions(post, locale, base62_sha1s, uploads_by_base62_sha1)
- reusable_descriptions = reusable_descriptions_for(post.id, locale, base62_sha1s)
- return 0 if reusable_descriptions.blank?
+ def reuse_captions(post, locale, base62_sha1s, uploads_by_base62_sha1)
+ reusable_captions = reusable_captions_for(post.id, locale, base62_sha1s)
+ return 0 if reusable_captions.blank?
reused_count = 0
- reusable_descriptions.each do |base62_sha1, description|
+ reusable_captions.each do |base62_sha1, description|
upload = uploads_by_base62_sha1[base62_sha1]
next if upload.blank? || !captionable_upload?(upload, post)
- record_reused_description(post, upload, base62_sha1, locale, description)
+ record_reused_caption(post, upload, base62_sha1, locale, description)
reused_count += 1
end
reused_count
end
- def reusable_descriptions_for(post_id, locale, base62_sha1s)
+ def reusable_captions_for(post_id, locale, base62_sha1s)
DB
.query(<<~SQL, post_id: post_id, locale: locale, base62_sha1s: base62_sha1s)
SELECT DISTINCT ON (base62_sha1) base62_sha1, description
- FROM ai_post_image_descriptions
+ FROM ai_post_image_captions
WHERE locale = :locale
AND base62_sha1 IN (:base62_sha1s)
AND post_id <> :post_id
@@ -471,7 +472,7 @@ module DiscourseAi
DB.exec(
<<~SQL,
- INSERT INTO ai_post_image_descriptions
+ INSERT INTO ai_post_image_captions
(
post_id,
upload_id,
@@ -500,7 +501,7 @@ module DiscourseAi
ON CONFLICT (post_id, locale, base62_sha1) DO UPDATE SET
upload_id = EXCLUDED.upload_id,
description = EXCLUDED.description,
- attempts = ai_post_image_descriptions.attempts + 1,
+ attempts = ai_post_image_captions.attempts + 1,
last_attempted_at = EXCLUDED.last_attempted_at,
last_error = EXCLUDED.last_error,
updated_at = EXCLUDED.updated_at
@@ -515,12 +516,12 @@ module DiscourseAi
)
end
- def record_reused_description(post, upload, base62_sha1, locale, description)
+ def record_reused_caption(post, upload, base62_sha1, locale, description)
now = Time.zone.now
DB.exec(
<<~SQL,
- INSERT INTO ai_post_image_descriptions
+ INSERT INTO ai_post_image_captions
(
post_id,
upload_id,
@@ -560,7 +561,7 @@ module DiscourseAi
end
def image_caption_agent
- AiAgent.find_by(id: SiteSetting.ai_helper_image_caption_agent.to_i)
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent.to_i)
end
def image_caption_llm_model(agent = image_caption_agent)
@@ -577,7 +578,7 @@ module DiscourseAi
end
def delete_for_post(post_id)
- AiPostImageDescription.where(post_id: post_id).delete_all
+ AiPostImageCaption.where(post_id: post_id).delete_all
end
def aria_description(description, locale)
@@ -625,15 +626,15 @@ module DiscourseAi
Upload.sha1_from_short_path(path)
end
- def delete_removed_descriptions(post, locale, base62_sha1s)
- scope = AiPostImageDescription.where(post_id: post.id)
+ def delete_removed_captions(post, locale, base62_sha1s)
+ scope = AiPostImageCaption.where(post_id: post.id)
scope = scope.where(locale: locale) if locale != original_locale(post)
scope = scope.where.not(base62_sha1: base62_sha1s) if base62_sha1s.present?
scope.delete_all
end
- def remove_existing_description_metadata(doc)
- doc.css("span.#{DESCRIPTION_CLASS}").remove
+ def remove_existing_caption_metadata(doc)
+ doc.css("span.#{CAPTION_CLASS}, span.#{LEGACY_DESCRIPTION_CLASS}").remove
doc.css("[aria-describedby]").each { |node| remove_ai_describedby(node) }
@@ -649,7 +650,9 @@ module DiscourseAi
def remove_ai_describedby(node)
ids =
- node["aria-describedby"].to_s.split.reject { |id| id.start_with?(DESCRIPTION_ID_PREFIX) }
+ node["aria-describedby"].to_s.split.reject do |id|
+ id.start_with?(CAPTION_ID_PREFIX) || id.start_with?(LEGACY_DESCRIPTION_ID_PREFIX)
+ end
if ids.present?
node["aria-describedby"] = ids.join(" ")
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index 304a92edc83..05ea203687d 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -128,6 +128,7 @@ after_initialize do
].each { |a_module| a_module.inject_into(self) }
register_problem_check ProblemCheck::AiLlmStatus
+ register_problem_check ProblemCheck::AiImageCaptionAgent
#register_problem_check ProblemCheck::AiCreditSoftLimit
#register_problem_check ProblemCheck::AiCreditHardLimit
@@ -158,7 +159,7 @@ after_initialize do
on(:post_destroyed) do |post|
if !Post.with_deleted.exists?(post.id)
DiscourseAi::AiApiAuditLogCleaner.delete_for_post(post.id)
- DiscourseAi::PostImageDescriptions.delete_for_post(post.id)
+ DiscourseAi::PostImageCaptions.delete_for_post(post.id)
end
end
@@ -195,23 +196,23 @@ after_initialize do
end
on(:post_process_cooked) do |doc, post|
- DiscourseAi::PostImageDescriptions.process_cooked(
+ DiscourseAi::PostImageCaptions.process_cooked(
doc,
post,
- locale: DiscourseAi::PostImageDescriptions.original_locale(post),
+ locale: DiscourseAi::PostImageCaptions.original_locale(post),
)
end
on(:post_process_localized_cooked) do |doc, post, post_localization|
- DiscourseAi::PostImageDescriptions.process_cooked(doc, post, locale: post_localization.locale)
+ DiscourseAi::PostImageCaptions.process_cooked(doc, post, locale: post_localization.locale)
end
register_modifier(:post_search_index_text) do |text, post_id, cooked, locale|
- DiscourseAi::PostImageDescriptions.append_to_search_text(text, post_id, cooked, locale: locale)
+ DiscourseAi::PostImageCaptions.append_to_search_text(text, post_id, cooked, locale: locale)
end
on(:reduce_cooked) do |doc, _post|
- DiscourseAi::PostImageDescriptions.remove_existing_description_metadata(doc)
+ DiscourseAi::PostImageCaptions.remove_existing_caption_metadata(doc)
end
add_api_key_scope(:ai, { update_agents: { actions: %w[discourse_ai/admin/ai_agents#update] } })
diff --git a/plugins/discourse-ai/spec/configuration/feature_spec.rb b/plugins/discourse-ai/spec/configuration/feature_spec.rb
index 99e681148f3..49c86d6901b 100644
--- a/plugins/discourse-ai/spec/configuration/feature_spec.rb
+++ b/plugins/discourse-ai/spec/configuration/feature_spec.rb
@@ -1,8 +1,8 @@
# frozen_string_literal: true
RSpec.describe DiscourseAi::Configuration::Feature do
- fab!(:llm_model)
- fab!(:ai_agent) { Fabricate(:ai_agent, default_llm_id: llm_model.id) }
+ fab!(:llm_model) { Fabricate(:llm_model, vision_enabled: true) }
+ fab!(:ai_agent) { Fabricate(:ai_agent, default_llm_id: llm_model.id, vision_enabled: true) }
before { assign_fake_provider_to(:ai_default_llm_model) }
@@ -194,6 +194,35 @@ RSpec.describe DiscourseAi::Configuration::Feature do
expect(bot_feature.agent_ids).to include(multi_permission_agent.id)
end
+
+ it "does not include the image caption agent" do
+ pm_agent.update!(default_llm_id: bot_llm.id, vision_enabled: true)
+ bot_llm.update!(vision_enabled: true)
+ SiteSetting.ai_image_caption_agent = pm_agent.id
+
+ expect(bot_feature.agent_ids).not_to include(pm_agent.id)
+ end
+ end
+
+ describe ".image_caption_features" do
+ let(:image_caption_feature) { described_class.image_caption_features.first }
+
+ it "returns the post image captions feature with the image caption module configuration" do
+ expect(image_caption_feature.name).to eq("post_image_captions")
+ expect(image_caption_feature.agent_setting).to eq("ai_image_caption_agent")
+ expect(image_caption_feature.module_id).to eq(
+ DiscourseAi::Configuration::Module::IMAGE_CAPTION_ID,
+ )
+ expect(image_caption_feature.module_name).to eq(
+ DiscourseAi::Configuration::Module::IMAGE_CAPTION,
+ )
+ end
+
+ it "uses the selected image caption agent" do
+ SiteSetting.ai_image_caption_agent = ai_agent.id
+
+ expect(image_caption_feature.agent_ids).to eq([ai_agent.id])
+ end
end
describe "#agent_ids" do
@@ -257,11 +286,12 @@ RSpec.describe DiscourseAi::Configuration::Feature do
it "returns all features using a specific agent" do
SiteSetting.ai_summarization_agent = ai_agent.id
SiteSetting.ai_helper_proofreader_agent = ai_agent.id
+ SiteSetting.ai_image_caption_agent = ai_agent.id
SiteSetting.ai_translation_locale_detector_agent = 999
features = described_class.find_features_using(agent_id: ai_agent.id)
- expect(features.map(&:name)).to include("topic_summaries", "proofread")
+ expect(features.map(&:name)).to include("topic_summaries", "proofread", "post_image_captions")
expect(features.map(&:name)).not_to include("locale_detector")
end
end
diff --git a/plugins/discourse-ai/spec/configuration/image_caption_agent_validator_spec.rb b/plugins/discourse-ai/spec/configuration/image_caption_agent_validator_spec.rb
new file mode 100644
index 00000000000..bac38694523
--- /dev/null
+++ b/plugins/discourse-ai/spec/configuration/image_caption_agent_validator_spec.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Configuration::ImageCaptionAgentValidator do
+ fab!(:vision_llm) do
+ Fabricate(:llm_model, display_name: "Vision model", name: "vision-model", vision_enabled: true)
+ end
+ fab!(:text_llm) do
+ Fabricate(:llm_model, display_name: "Text model", name: "text-model", vision_enabled: false)
+ end
+
+ fab!(:valid_agent) do
+ Fabricate(:ai_agent, enabled: true, vision_enabled: true, default_llm_id: vision_llm.id)
+ end
+ fab!(:disabled_agent) do
+ Fabricate(:ai_agent, enabled: false, vision_enabled: true, default_llm_id: vision_llm.id)
+ end
+ fab!(:non_vision_agent) do
+ Fabricate(:ai_agent, enabled: true, vision_enabled: false, default_llm_id: vision_llm.id)
+ end
+ fab!(:text_llm_agent) do
+ Fabricate(:ai_agent, enabled: true, vision_enabled: true, default_llm_id: text_llm.id)
+ end
+ fab!(:missing_llm_agent) do
+ Fabricate(:ai_agent, enabled: true, vision_enabled: true, default_llm_id: -99_999)
+ end
+
+ before { enable_current_plugin }
+
+ let(:validator) { described_class.new(name: :ai_image_caption_agent) }
+
+ it "accepts the default image caption agent setting value" do
+ expect(validator.valid_value?("-26")).to eq(true)
+ end
+
+ it "accepts an enabled vision agent that uses a vision-capable LLM" do
+ expect(validator.valid_value?(valid_agent.id)).to eq(true)
+ end
+
+ it "rejects a missing agent" do
+ expect(validator.valid_value?(-99_999)).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("discourse_ai.image_caption.configuration.agent_missing"),
+ )
+ end
+
+ it "accepts an agent that is disabled for AI bot" do
+ expect(validator.valid_value?(disabled_agent.id)).to eq(true)
+ end
+
+ it "rejects an agent without vision enabled" do
+ expect(validator.valid_value?(non_vision_agent.id)).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("discourse_ai.image_caption.configuration.agent_vision_disabled"),
+ )
+ end
+
+ it "rejects an agent that resolves to an LLM without vision enabled" do
+ expect(validator.valid_value?(text_llm_agent.id)).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("discourse_ai.image_caption.configuration.llm_vision_disabled"),
+ )
+ end
+
+ it "rejects an agent that resolves to a missing LLM" do
+ expect(validator.valid_value?(missing_llm_agent.id)).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("discourse_ai.image_caption.configuration.llm_missing"),
+ )
+ end
+
+ it "validates assignments to the image caption agent site setting" do
+ SiteSetting.ai_image_caption_agent = valid_agent.id
+
+ expect(SiteSetting.ai_image_caption_agent).to eq(valid_agent.id.to_s)
+ expect { SiteSetting.ai_image_caption_agent = text_llm_agent.id }.to raise_error(
+ Discourse::InvalidParameters,
+ /vision-capable LLM/,
+ )
+ end
+end
diff --git a/plugins/discourse-ai/spec/configuration/image_caption_enabled_validator_spec.rb b/plugins/discourse-ai/spec/configuration/image_caption_enabled_validator_spec.rb
new file mode 100644
index 00000000000..b42b9d92e34
--- /dev/null
+++ b/plugins/discourse-ai/spec/configuration/image_caption_enabled_validator_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Configuration::ImageCaptionEnabledValidator do
+ fab!(:vision_llm) do
+ Fabricate(:llm_model, display_name: "Vision model", name: "vision-model", vision_enabled: true)
+ end
+ fab!(:valid_agent) do
+ Fabricate(:ai_agent, enabled: false, vision_enabled: true, default_llm_id: vision_llm.id)
+ end
+ fab!(:non_vision_agent) do
+ Fabricate(:ai_agent, enabled: true, vision_enabled: false, default_llm_id: vision_llm.id)
+ end
+
+ before { enable_current_plugin }
+
+ after do
+ SiteSetting.ai_post_image_captions_enabled = false
+ SiteSetting.remove_override!(:ai_image_caption_agent)
+ SiteSetting.refresh!
+ end
+
+ def set_caption_agent(agent)
+ SiteSetting.provider.save("ai_image_caption_agent", agent.id, SiteSetting.types[:enum])
+ SiteSetting.refresh!
+ end
+
+ it "accepts an agent that is disabled for AI bot" do
+ set_caption_agent(valid_agent)
+
+ SiteSetting.ai_post_image_captions_enabled = true
+
+ expect(SiteSetting.ai_post_image_captions_enabled).to eq(true)
+ end
+
+ it "rejects enabling image captions when the selected agent cannot generate image captions" do
+ set_caption_agent(non_vision_agent)
+
+ expect { SiteSetting.ai_post_image_captions_enabled = true }.to raise_error(
+ Discourse::InvalidParameters,
+ /image uploads enabled/,
+ )
+ end
+
+ it "allows disabling image captions when the selected agent cannot generate image captions" do
+ set_caption_agent(non_vision_agent)
+
+ SiteSetting.ai_post_image_captions_enabled = false
+
+ expect(SiteSetting.ai_post_image_captions_enabled).to eq(false)
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/regular/generate_post_image_descriptions_spec.rb b/plugins/discourse-ai/spec/jobs/regular/generate_post_image_captions_spec.rb
similarity index 75%
rename from plugins/discourse-ai/spec/jobs/regular/generate_post_image_descriptions_spec.rb
rename to plugins/discourse-ai/spec/jobs/regular/generate_post_image_captions_spec.rb
index 22293a40d0b..7662e6f8d87 100644
--- a/plugins/discourse-ai/spec/jobs/regular/generate_post_image_descriptions_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/regular/generate_post_image_captions_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe Jobs::GeneratePostImageDescriptions do
+describe Jobs::GeneratePostImageCaptions do
fab!(:upload) do
UploadCreator.new(
file_from_fixtures(
@@ -17,11 +17,11 @@ describe Jobs::GeneratePostImageDescriptions do
enable_current_plugin
llm_model = assign_fake_provider_to(:ai_default_llm_model)
llm_model.update!(vision_enabled: true)
- AiAgent.find_by(id: SiteSetting.ai_helper_image_caption_agent).update!(
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent).update!(
enabled: true,
vision_enabled: true,
)
- SiteSetting.ai_post_image_descriptions_enabled = true
+ SiteSetting.ai_post_image_captions_enabled = true
SiteSetting.ai_helper_enabled = true
SearchIndexer.enable
post.update_column(:cooked, post.cook(post.raw, topic_id: post.topic_id))
@@ -47,10 +47,10 @@ describe Jobs::GeneratePostImageDescriptions do
end
end
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
prompt = prompts.first
- expect(image_description.description).to eq(description)
+ expect(image_caption.description).to eq(description)
expect(post.reload.post_search_data.raw_data).to include(description)
expect(prompt.post_id).to eq(post.id)
expect(prompt.topic_id).to eq(post.topic_id)
@@ -64,7 +64,7 @@ describe Jobs::GeneratePostImageDescriptions do
)
existing_post.link_post_uploads
- AiPostImageDescription.create!(
+ AiPostImageCaption.create!(
post_id: existing_post.id,
upload_id: upload.id,
base62_sha1: upload.base62_sha1,
@@ -83,10 +83,10 @@ describe Jobs::GeneratePostImageDescriptions do
expect(canned_response.completions).to eq(0)
end
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
- expect(image_description.description).to eq("A reusable description")
- expect(image_description.attempts).to eq(0)
+ expect(image_caption.description).to eq("A reusable description")
+ expect(image_caption.attempts).to eq(0)
end
it "replaces retryable rows with reused descriptions", :aggregate_failures do
@@ -97,7 +97,7 @@ describe Jobs::GeneratePostImageDescriptions do
)
existing_post.link_post_uploads
- AiPostImageDescription.create!(
+ AiPostImageCaption.create!(
post_id: existing_post.id,
upload_id: upload.id,
base62_sha1: upload.base62_sha1,
@@ -106,7 +106,7 @@ describe Jobs::GeneratePostImageDescriptions do
attempts: 1,
)
- AiPostImageDescription.create!(
+ AiPostImageCaption.create!(
post_id: post.id,
upload_id: upload.id,
base62_sha1: upload.base62_sha1,
@@ -127,12 +127,12 @@ describe Jobs::GeneratePostImageDescriptions do
expect(canned_response.completions).to eq(0)
end
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
- expect(image_description.description).to eq("A reusable retry description")
- expect(image_description.attempts).to eq(0)
- expect(image_description.last_attempted_at).to be_nil
- expect(image_description.last_error).to be_nil
+ expect(image_caption.description).to eq("A reusable retry description")
+ expect(image_caption.attempts).to eq(0)
+ expect(image_caption.last_attempted_at).to be_nil
+ expect(image_caption.last_error).to be_nil
end
it "ignores images that are no longer in the post" do
@@ -146,7 +146,7 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
- expect(AiPostImageDescription.exists?(post_id: post.id)).to eq(false)
+ expect(AiPostImageCaption.exists?(post_id: post.id)).to eq(false)
end
it "records uncaptionable backfill candidates" do
@@ -154,11 +154,11 @@ describe Jobs::GeneratePostImageDescriptions do
described_class.new.execute(post_id: post.id, locale: SiteSetting.default_locale)
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
- expect(image_description.description).to be_nil
- expect(image_description.attempts).to eq(1)
- expect(image_description.last_error).to eq("no_post_image_nodes")
+ expect(image_caption.description).to be_nil
+ expect(image_caption.attempts).to eq(1)
+ expect(image_caption.last_error).to eq("no_post_image_nodes")
end
it "records blank responses without retrying immediately", :aggregate_failures do
@@ -170,11 +170,11 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
- expect(image_description.description).to be_nil
- expect(image_description.attempts).to eq(1)
- expect(image_description.last_error).to eq("blank_response")
+ expect(image_caption.description).to be_nil
+ expect(image_caption.attempts).to eq(1)
+ expect(image_caption.last_error).to eq("blank_response")
DiscourseAi::Completions::Llm.with_prepared_responses(["second attempt"]) do
described_class.new.execute(
@@ -184,10 +184,10 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
- expect(image_description.description).to be_nil
- expect(image_description.attempts).to eq(1)
+ expect(image_caption.description).to be_nil
+ expect(image_caption.attempts).to eq(1)
end
it "updates retryable attempt rows", :aggregate_failures do
@@ -199,7 +199,7 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
- AiPostImageDescription.where(
+ AiPostImageCaption.where(
post_id: post.id,
locale: SiteSetting.default_locale,
base62_sha1: upload.base62_sha1,
@@ -213,16 +213,16 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
- image_description =
- AiPostImageDescription.find_by(
+ image_caption =
+ AiPostImageCaption.find_by(
post_id: post.id,
locale: SiteSetting.default_locale,
base62_sha1: upload.base62_sha1,
)
- expect(image_description.description).to eq("second attempt")
- expect(image_description.attempts).to eq(2)
- expect(image_description.last_error).to be_nil
+ expect(image_caption.description).to eq("second attempt")
+ expect(image_caption.attempts).to eq(2)
+ expect(image_caption.last_error).to be_nil
end
it "limits generated descriptions per post", :aggregate_failures do
@@ -236,7 +236,7 @@ describe Jobs::GeneratePostImageDescriptions do
"second-image.png",
).create_for(Discourse.system_user.id)
- SiteSetting.ai_post_image_descriptions_per_post_limit = 1
+ SiteSetting.ai_post_image_captions_per_post_limit = 1
post.update!(
raw:
"![first image|200x200](#{upload.short_url})\n\n![second image|200x200](#{second_upload.short_url})",
@@ -257,14 +257,14 @@ describe Jobs::GeneratePostImageDescriptions do
end
expect(
- AiPostImageDescription.exists?(
+ AiPostImageCaption.exists?(
post_id: post.id,
base62_sha1: upload.base62_sha1,
description: "first generated description",
),
).to eq(true)
expect(
- AiPostImageDescription.exists?(post_id: post.id, base62_sha1: second_upload.base62_sha1),
+ AiPostImageCaption.exists?(post_id: post.id, base62_sha1: second_upload.base62_sha1),
).to eq(false)
end
@@ -287,7 +287,7 @@ describe Jobs::GeneratePostImageDescriptions do
post.link_post_uploads
DiscourseAi::Completions::Llm.with_prepared_responses(
- ["A generated first image description", StandardError.new("rate limited")],
+ ["A generated first image caption", StandardError.new("rate limited")],
) do
described_class.new.execute(
post_id: post.id,
@@ -296,11 +296,11 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
+ expect(AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id).description).to eq(
+ "A generated first image caption",
+ )
expect(
- AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id).description,
- ).to eq("A generated first image description")
- expect(
- AiPostImageDescription.find_by(post_id: post.id, upload_id: second_upload.id).last_error,
+ AiPostImageCaption.find_by(post_id: post.id, upload_id: second_upload.id).last_error,
).to eq("rate limited")
end
@@ -317,10 +317,10 @@ describe Jobs::GeneratePostImageDescriptions do
expect(canned_response.completions).to eq(0)
end
- image_description = AiPostImageDescription.find_by(post_id: post.id, upload_id: upload.id)
+ image_caption = AiPostImageCaption.find_by(post_id: post.id, upload_id: upload.id)
- expect(image_description.description).to be_nil
- expect(image_description.last_error).to eq("upload_not_captionable")
+ expect(image_caption.description).to be_nil
+ expect(image_caption.last_error).to eq("upload_not_captionable")
end
it "skips generation when credits are unavailable" do
@@ -334,7 +334,7 @@ describe Jobs::GeneratePostImageDescriptions do
)
end
- expect(AiPostImageDescription.exists?(post_id: post.id)).to eq(false)
+ expect(AiPostImageCaption.exists?(post_id: post.id)).to eq(false)
end
it "keeps localized descriptions out of original search data", :aggregate_failures do
@@ -349,7 +349,7 @@ describe Jobs::GeneratePostImageDescriptions do
end
expect(
- AiPostImageDescription.exists?(post_id: post.id, locale: "ja", description: description),
+ AiPostImageCaption.exists?(post_id: post.id, locale: "ja", description: description),
).to eq(true)
expect(post.reload.post_search_data.raw_data).not_to include(description)
end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/post_image_descriptions_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/post_image_captions_backfill_spec.rb
similarity index 64%
rename from plugins/discourse-ai/spec/jobs/scheduled/post_image_descriptions_backfill_spec.rb
rename to plugins/discourse-ai/spec/jobs/scheduled/post_image_captions_backfill_spec.rb
index e800537b501..a86a8778179 100644
--- a/plugins/discourse-ai/spec/jobs/scheduled/post_image_descriptions_backfill_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/scheduled/post_image_captions_backfill_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe Jobs::PostImageDescriptionsBackfill do
+describe Jobs::PostImageCaptionsBackfill do
fab!(:upload) do
UploadCreator.new(
file_from_fixtures(
@@ -17,11 +17,11 @@ describe Jobs::PostImageDescriptionsBackfill do
enable_current_plugin
llm_model = assign_fake_provider_to(:ai_default_llm_model)
llm_model.update!(vision_enabled: true)
- AiAgent.find_by(id: SiteSetting.ai_helper_image_caption_agent).update!(
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent).update!(
enabled: true,
vision_enabled: true,
)
- SiteSetting.ai_post_image_descriptions_enabled = true
+ SiteSetting.ai_post_image_captions_enabled = true
SiteSetting.ai_helper_enabled = true
post.update_column(:cooked, post.cook(post.raw, topic_id: post.topic_id))
post.link_post_uploads
@@ -29,7 +29,7 @@ describe Jobs::PostImageDescriptionsBackfill do
end
def store_description(target_upload)
- AiPostImageDescription.upsert_all(
+ AiPostImageCaption.upsert_all(
[
{
post_id: post.id,
@@ -40,14 +40,14 @@ describe Jobs::PostImageDescriptionsBackfill do
attempts: 0,
},
],
- unique_by: DiscourseAi::PostImageDescriptions::LOOKUP_INDEX,
+ unique_by: DiscourseAi::PostImageCaptions::LOOKUP_INDEX,
)
end
def store_attempt(created_at:, target_post: nil, last_attempted_at: nil)
target_post ||= Fabricate(:post)
- AiPostImageDescription.create!(
+ AiPostImageCaption.create!(
post_id: target_post.id,
upload_id: upload.id,
base62_sha1: upload.base62_sha1,
@@ -60,27 +60,23 @@ describe Jobs::PostImageDescriptionsBackfill do
end
it "does nothing when backfill is disabled" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 0
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 0
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
- it "does nothing when post image descriptions are disabled" do
- SiteSetting.ai_post_image_descriptions_enabled = false
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ it "does nothing when post image captions are disabled" do
+ SiteSetting.ai_post_image_captions_enabled = false
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "enqueues posts without existing descriptions" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: SiteSetting.default_locale,
@@ -89,10 +85,10 @@ describe Jobs::PostImageDescriptionsBackfill do
end
it "enqueues one post when a low hourly backfill budget is unused" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 1
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 1
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: SiteSetting.default_locale,
@@ -102,13 +98,13 @@ describe Jobs::PostImageDescriptionsBackfill do
it "enqueues existing localized posts when localization is enabled" do
SiteSetting.content_localization_enabled = true
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 8
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 8
Fabricate(:post_localization, post: post, locale: "ja", raw: post.raw, cooked: post.cooked)
described_class.new.execute({})
jobs =
- Jobs::GeneratePostImageDescriptions
+ Jobs::GeneratePostImageCaptions
.jobs
.last(2)
.map { |job| job["args"].first.slice("post_id", "locale") }
@@ -120,31 +116,25 @@ describe Jobs::PostImageDescriptionsBackfill do
end
it "does not enqueue posts older than the backfill max age" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
- SiteSetting.ai_post_image_descriptions_backfill_max_age_days = 30
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_max_age_days = 30
post.update_column(:created_at, 31.days.ago)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "respects the hourly backfill budget" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 1
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 1
store_attempt(created_at: 10.minutes.ago)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "counts recent retry attempts against the backfill budget" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 1
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 1
store_attempt(created_at: 2.days.ago, last_attempted_at: 10.minutes.ago)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "does not repeatedly enqueue described posts with image attachments" do
@@ -167,24 +157,20 @@ describe Jobs::PostImageDescriptionsBackfill do
post.link_post_uploads
store_description(upload)
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "does not enqueue posts with an original locale description" do
store_description(upload)
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "does not immediately re-enqueue recently attempted posts" do
- AiPostImageDescription.upsert_all(
+ AiPostImageCaption.upsert_all(
[
{
post_id: post.id,
@@ -197,14 +183,12 @@ describe Jobs::PostImageDescriptionsBackfill do
last_error: "blank_response",
},
],
- unique_by: DiscourseAi::PostImageDescriptions::LOOKUP_INDEX,
+ unique_by: DiscourseAi::PostImageCaptions::LOOKUP_INDEX,
)
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "re-enqueues posts with retryable image attempts" do
@@ -226,7 +210,7 @@ describe Jobs::PostImageDescriptionsBackfill do
post.link_post_uploads
store_description(upload)
- AiPostImageDescription.upsert_all(
+ AiPostImageCaption.upsert_all(
[
{
post_id: post.id,
@@ -239,13 +223,13 @@ describe Jobs::PostImageDescriptionsBackfill do
last_error: "rate limited",
},
],
- unique_by: DiscourseAi::PostImageDescriptions::LOOKUP_INDEX,
+ unique_by: DiscourseAi::PostImageCaptions::LOOKUP_INDEX,
)
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: SiteSetting.default_locale,
@@ -254,20 +238,18 @@ describe Jobs::PostImageDescriptionsBackfill do
end
it "does not enqueue when credits are unavailable" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
LlmCreditAllocation.stubs(:credits_available?).returns(false)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
it "uses post image ids for backfill candidates" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
post.update_column(:cooked, "<p>No upload marker</p>")
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: SiteSetting.default_locale,
@@ -276,11 +258,9 @@ describe Jobs::PostImageDescriptionsBackfill do
end
it "does not enqueue attachment-only posts" do
- SiteSetting.ai_post_image_descriptions_backfill_hourly_rate = 4
+ SiteSetting.ai_post_image_captions_backfill_hourly_rate = 4
post.update_column(:image_upload_id, nil)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
- described_class.new.execute({})
- end
+ expect_not_enqueued_with(job: :generate_post_image_captions) { described_class.new.execute({}) }
end
end
diff --git a/plugins/discourse-ai/spec/lib/agents/image_captioner_spec.rb b/plugins/discourse-ai/spec/lib/agents/image_captioner_spec.rb
new file mode 100644
index 00000000000..11cfa749e71
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/image_captioner_spec.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Agents::ImageCaptioner do
+ it "enables image uploads by default" do
+ expect(described_class.vision_enabled).to eq(true)
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/post_image_descriptions_spec.rb b/plugins/discourse-ai/spec/lib/post_image_captions_spec.rb
similarity index 80%
rename from plugins/discourse-ai/spec/lib/post_image_descriptions_spec.rb
rename to plugins/discourse-ai/spec/lib/post_image_captions_spec.rb
index aa151fcb2c7..96eec574489 100644
--- a/plugins/discourse-ai/spec/lib/post_image_descriptions_spec.rb
+++ b/plugins/discourse-ai/spec/lib/post_image_captions_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscourseAi::PostImageDescriptions do
+describe DiscourseAi::PostImageCaptions do
fab!(:upload) { create_image_upload("100x100.jpg", "caption-image.jpg") }
fab!(:post) { Fabricate(:post, raw: "![user supplied|200x200](#{upload.short_url})") }
@@ -8,11 +8,11 @@ describe DiscourseAi::PostImageDescriptions do
enable_current_plugin
llm_model = assign_fake_provider_to(:ai_default_llm_model)
llm_model.update!(vision_enabled: true)
- AiAgent.find_by(id: SiteSetting.ai_helper_image_caption_agent).update!(
- enabled: true,
- vision_enabled: true,
- )
- SiteSetting.ai_post_image_descriptions_enabled = true
+ caption_agent =
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent.to_i) ||
+ Fabricate(:ai_agent, id: SiteSetting.ai_image_caption_agent.to_i)
+ caption_agent.update!(enabled: true, vision_enabled: true, default_llm_id: llm_model.id)
+ SiteSetting.ai_post_image_captions_enabled = true
SiteSetting.ai_helper_enabled = true
post.update_column(:cooked, post.cook(post.raw, topic_id: post.topic_id))
post.link_post_uploads
@@ -33,7 +33,7 @@ describe DiscourseAi::PostImageDescriptions do
end
def store_description(description, locale: SiteSetting.default_locale, target_upload: upload)
- AiPostImageDescription.upsert_all(
+ AiPostImageCaption.upsert_all(
[
{
post_id: post.id,
@@ -49,8 +49,8 @@ describe DiscourseAi::PostImageDescriptions do
end
it "supports ActiveRecord updates with a primary key" do
- image_description =
- AiPostImageDescription.create!(
+ image_caption =
+ AiPostImageCaption.create!(
post_id: post.id,
upload_id: upload.id,
base62_sha1: upload.base62_sha1,
@@ -58,12 +58,12 @@ describe DiscourseAi::PostImageDescriptions do
description: "An initial description",
)
- image_description.update!(description: "An updated description")
+ image_caption.update!(description: "An updated description")
- expect(image_description.reload.description).to eq("An updated description")
+ expect(image_caption.reload.description).to eq("An updated description")
end
- it "adds image description metadata without visible text", :aggregate_failures do
+ it "adds image caption metadata without visible text", :aggregate_failures do
description = "A lighthouse beside 字 on a sign"
store_description(description)
@@ -85,7 +85,7 @@ describe DiscourseAi::PostImageDescriptions do
).not_to include(description)
end
- it "strips image description metadata from email HTML", :aggregate_failures do
+ it "strips image caption metadata from email HTML", :aggregate_failures do
description = "A generated email-only 字 description"
store_description(description)
@@ -110,7 +110,7 @@ describe DiscourseAi::PostImageDescriptions do
post.link_post_uploads
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: SiteSetting.default_locale,
@@ -122,19 +122,26 @@ describe DiscourseAi::PostImageDescriptions do
end
end
- it "does not run when post image descriptions are disabled" do
- SiteSetting.ai_post_image_descriptions_enabled = false
+ it "does not run when post image captions are disabled" do
+ SiteSetting.ai_post_image_captions_enabled = false
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
+ expect_not_enqueued_with(job: :generate_post_image_captions) do
described_class.process_cooked(Nokogiri::HTML5.fragment(post.cooked), post, locale: "en")
end
end
- it "does not enqueue generation when the caption agent is disabled" do
- AiAgent.find_by(id: SiteSetting.ai_helper_image_caption_agent).update!(enabled: false)
+ it "enqueues generation when the caption agent is disabled for AI bot use" do
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent).update!(enabled: false)
- expect(described_class.generation_enabled?).to eq(false)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
+ expect(described_class.generation_enabled?).to eq(true)
+ expect_enqueued_with(
+ job: :generate_post_image_captions,
+ args: {
+ post_id: post.id,
+ locale: SiteSetting.default_locale,
+ base62_sha1s: [upload.base62_sha1],
+ },
+ ) do
described_class.process_cooked(
Nokogiri::HTML5.fragment(post.cooked),
post,
@@ -146,7 +153,7 @@ describe DiscourseAi::PostImageDescriptions do
it "does not enqueue generation while cooking old posts" do
post.update_columns(created_at: 2.days.ago, updated_at: 2.days.ago)
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
+ expect_not_enqueued_with(job: :generate_post_image_captions) do
processor = CookedPostProcessor.new(post)
processor.post_process
end
@@ -156,7 +163,7 @@ describe DiscourseAi::PostImageDescriptions do
post.update_columns(created_at: 2.days.ago, updated_at: Time.zone.now)
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: SiteSetting.default_locale,
@@ -169,7 +176,7 @@ describe DiscourseAi::PostImageDescriptions do
end
it "preserves non-AI image aria descriptions when disabled", :aggregate_failures do
- SiteSetting.ai_post_image_descriptions_enabled = false
+ SiteSetting.ai_post_image_captions_enabled = false
doc =
Nokogiri::HTML5.fragment(
"<a class='lightbox' aria-description='custom lightbox'>" \
@@ -193,7 +200,7 @@ describe DiscourseAi::PostImageDescriptions do
whisper.update_column(:cooked, post.cooked)
whisper.link_post_uploads
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
+ expect_not_enqueued_with(job: :generate_post_image_captions) do
described_class.process_cooked(
Nokogiri::HTML5.fragment(pm_post.cooked),
pm_post,
@@ -210,7 +217,7 @@ describe DiscourseAi::PostImageDescriptions do
it "ignores image nodes without post upload references" do
unrelated_upload = create_image_upload("An image of discobot in action.png", "unrelated.png")
- expect_not_enqueued_with(job: :generate_post_image_descriptions) do
+ expect_not_enqueued_with(job: :generate_post_image_captions) do
described_class.process_cooked(
Nokogiri::HTML5.fragment(
"<img src='https://example.com/image.png' data-base62-sha1='#{unrelated_upload.base62_sha1}'>" \
@@ -222,7 +229,7 @@ describe DiscourseAi::PostImageDescriptions do
end
end
- it "adds current image descriptions to search text" do
+ it "adds current image captions to search text" do
default_description = "A searchable 字 description"
japanese_description = "A Japanese 字 description"
store_description(default_description)
@@ -247,18 +254,14 @@ describe DiscourseAi::PostImageDescriptions do
described_class.process_cooked(Nokogiri::HTML5.fragment(post.cooked), post, locale: "ja")
expect(
- AiPostImageDescription.exists?(
+ AiPostImageCaption.exists?(
post_id: post.id,
locale: SiteSetting.default_locale,
base62_sha1: upload.base62_sha1,
),
).to eq(true)
expect(
- AiPostImageDescription.exists?(
- post_id: post.id,
- locale: "ja",
- base62_sha1: upload.base62_sha1,
- ),
+ AiPostImageCaption.exists?(post_id: post.id, locale: "ja", base62_sha1: upload.base62_sha1),
).to eq(false)
end
@@ -285,7 +288,7 @@ describe DiscourseAi::PostImageDescriptions do
Fabricate(:post_localization, post: post, locale: "ja", raw: post.raw, cooked: post.cooked)
expect_enqueued_with(
- job: :generate_post_image_descriptions,
+ job: :generate_post_image_captions,
args: {
post_id: post.id,
locale: "ja",
@@ -297,7 +300,7 @@ describe DiscourseAi::PostImageDescriptions do
image = doc.at_css("img[data-base62-sha1='#{upload.base62_sha1}']")
expect(image["aria-description"]).to include(description)
- expect(AiPostImageDescription.exists?(post_id: post.id, locale: "ja")).to eq(false)
+ expect(AiPostImageCaption.exists?(post_id: post.id, locale: "ja")).to eq(false)
end
it "deletes descriptions after all post images are removed" do
@@ -305,18 +308,18 @@ describe DiscourseAi::PostImageDescriptions do
described_class.process_cooked(Nokogiri::HTML5.fragment("<p>No image</p>"), post, locale: "en")
- expect(AiPostImageDescription.exists?(post_id: post.id, base62_sha1: upload.base62_sha1)).to eq(
+ expect(AiPostImageCaption.exists?(post_id: post.id, base62_sha1: upload.base62_sha1)).to eq(
false,
)
end
it "keeps stored descriptions when the feature is disabled" do
store_description("A stored description")
- SiteSetting.ai_post_image_descriptions_enabled = false
+ SiteSetting.ai_post_image_captions_enabled = false
described_class.process_cooked(Nokogiri::HTML5.fragment("<p>No image</p>"), post, locale: "en")
- expect(AiPostImageDescription.exists?(post_id: post.id, base62_sha1: upload.base62_sha1)).to eq(
+ expect(AiPostImageCaption.exists?(post_id: post.id, base62_sha1: upload.base62_sha1)).to eq(
true,
)
end
@@ -327,10 +330,10 @@ describe DiscourseAi::PostImageDescriptions do
PostDestroyer.new(admin, post).destroy
- expect(AiPostImageDescription.exists?(post_id: post.id)).to eq(true)
+ expect(AiPostImageCaption.exists?(post_id: post.id)).to eq(true)
PostDestroyer.new(admin, post.reload, force_destroy: true).destroy
- expect(AiPostImageDescription.exists?(post_id: post.id)).to eq(false)
+ expect(AiPostImageCaption.exists?(post_id: post.id)).to eq(false)
end
end
diff --git a/plugins/discourse-ai/spec/requests/post_image_descriptions_controller_spec.rb b/plugins/discourse-ai/spec/requests/post_image_captions_controller_spec.rb
similarity index 60%
rename from plugins/discourse-ai/spec/requests/post_image_descriptions_controller_spec.rb
rename to plugins/discourse-ai/spec/requests/post_image_captions_controller_spec.rb
index 564d3d0cc3c..74f1c1160a8 100644
--- a/plugins/discourse-ai/spec/requests/post_image_descriptions_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/post_image_captions_controller_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe DiscourseAi::PostImageDescriptionsController do
+describe DiscourseAi::PostImageCaptionsController do
fab!(:admin)
fab!(:upload) do
UploadCreator.new(
@@ -18,7 +18,8 @@ describe DiscourseAi::PostImageDescriptionsController do
before do
enable_current_plugin
- SiteSetting.ai_post_image_descriptions_enabled = true
+ configure_valid_caption_agent
+ SiteSetting.ai_post_image_captions_enabled = true
SearchIndexer.enable
post.update_column(:cooked, post.cook(post.raw, topic_id: post.topic_id))
post.link_post_uploads
@@ -26,13 +27,13 @@ describe DiscourseAi::PostImageDescriptionsController do
after { SearchIndexer.disable }
- def store_description(
+ def store_caption(
description,
target_post: post,
target_upload: upload,
locale: SiteSetting.default_locale
)
- AiPostImageDescription.upsert_all(
+ AiPostImageCaption.upsert_all(
[
{
post_id: target_post.id,
@@ -43,14 +44,23 @@ describe DiscourseAi::PostImageDescriptionsController do
attempts: 0,
},
],
- unique_by: DiscourseAi::PostImageDescriptions::LOOKUP_INDEX,
+ unique_by: DiscourseAi::PostImageCaptions::LOOKUP_INDEX,
)
end
+ def configure_valid_caption_agent
+ llm_model = assign_fake_provider_to(:ai_default_llm_model)
+ llm_model.update!(vision_enabled: true)
+ caption_agent =
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent.to_i) ||
+ Fabricate(:ai_agent, id: SiteSetting.ai_image_caption_agent.to_i)
+ caption_agent.update!(enabled: true, vision_enabled: true, default_llm_id: llm_model.id)
+ end
+
describe "#index" do
before { sign_in(admin) }
- it "returns editable descriptions for current post images", :aggregate_failures do
+ it "returns editable captions for current post images", :aggregate_failures do
description = "A generated 字 description"
stale_upload =
UploadCreator.new(
@@ -62,22 +72,22 @@ describe DiscourseAi::PostImageDescriptionsController do
"stale-caption-image.jpg",
).create_for(admin.id)
- store_description(description)
- store_description("A stale description", target_upload: stale_upload)
+ store_caption(description)
+ store_caption("A stale description", target_upload: stale_upload)
- get "/discourse-ai/post-image-descriptions/#{post.id}.json"
+ get "/discourse-ai/post-image-captions/#{post.id}.json"
expect(response.status).to eq(200)
- expect(response.parsed_body["descriptions"]).to contain_exactly(
+ expect(response.parsed_body["captions"]).to contain_exactly(
{ "base62_sha1" => upload.base62_sha1, "description" => description },
)
end
it "requires permission to edit the post" do
sign_in(Fabricate(:user))
- store_description("A generated description")
+ store_caption("A generated description")
- get "/discourse-ai/post-image-descriptions/#{post.id}.json"
+ get "/discourse-ai/post-image-captions/#{post.id}.json"
expect(response.status).to eq(403)
end
@@ -86,11 +96,11 @@ describe DiscourseAi::PostImageDescriptionsController do
describe "#update" do
before { sign_in(admin) }
- it "updates the description and refreshes derived content", :aggregate_failures do
- store_description("The old description")
+ it "updates the caption and refreshes derived content", :aggregate_failures do
+ store_caption("The old description")
expect_enqueued_with(job: :process_post, args: { post_id: post.id }) do
- put "/discourse-ai/post-image-descriptions/#{post.id}/#{upload.base62_sha1}.json",
+ put "/discourse-ai/post-image-captions/#{post.id}/#{upload.base62_sha1}.json",
params: {
description: "An edited 字 description",
}
@@ -102,10 +112,7 @@ describe DiscourseAi::PostImageDescriptionsController do
"description" => "An edited 字 description",
)
expect(
- AiPostImageDescription.find_by(
- post_id: post.id,
- base62_sha1: upload.base62_sha1,
- ).description,
+ AiPostImageCaption.find_by(post_id: post.id, base62_sha1: upload.base62_sha1).description,
).to eq("An edited 字 description")
expect(post.post_search_data.raw_data).to include("An edited 字 description")
@@ -115,7 +122,7 @@ describe DiscourseAi::PostImageDescriptionsController do
end
it "returns not found for images without an editable row" do
- put "/discourse-ai/post-image-descriptions/#{post.id}/#{upload.base62_sha1}.json",
+ put "/discourse-ai/post-image-captions/#{post.id}/#{upload.base62_sha1}.json",
params: {
description: "A new description",
}
@@ -123,12 +130,12 @@ describe DiscourseAi::PostImageDescriptionsController do
expect(response.status).to eq(404)
end
- it "validates description length" do
- store_description("The old description")
+ it "validates caption length" do
+ store_caption("The old description")
- put "/discourse-ai/post-image-descriptions/#{post.id}/#{upload.base62_sha1}.json",
+ put "/discourse-ai/post-image-captions/#{post.id}/#{upload.base62_sha1}.json",
params: {
- description: "x" * (DiscourseAi::PostImageDescriptions::MAX_DESCRIPTION_LENGTH + 1),
+ description: "x" * (DiscourseAi::PostImageCaptions::MAX_CAPTION_LENGTH + 1),
}
expect(response.status).to eq(422)
diff --git a/plugins/discourse-ai/spec/requests/post_image_descriptions_rss_spec.rb b/plugins/discourse-ai/spec/requests/post_image_captions_rss_spec.rb
similarity index 66%
rename from plugins/discourse-ai/spec/requests/post_image_descriptions_rss_spec.rb
rename to plugins/discourse-ai/spec/requests/post_image_captions_rss_spec.rb
index 47f00f667e3..bac133c1359 100644
--- a/plugins/discourse-ai/spec/requests/post_image_descriptions_rss_spec.rb
+++ b/plugins/discourse-ai/spec/requests/post_image_captions_rss_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe "AI post image descriptions in RSS" do
+describe "AI post image captions in RSS" do
fab!(:upload) do
UploadCreator.new(
file_from_fixtures(
@@ -16,14 +16,24 @@ describe "AI post image descriptions in RSS" do
before do
enable_current_plugin
- SiteSetting.ai_post_image_descriptions_enabled = true
+ configure_valid_caption_agent
+ SiteSetting.ai_post_image_captions_enabled = true
post.update_column(:cooked, post.cook(post.raw, topic_id: post.topic_id))
post.link_post_uploads
end
+ def configure_valid_caption_agent
+ llm_model = assign_fake_provider_to(:ai_default_llm_model)
+ llm_model.update!(vision_enabled: true)
+ caption_agent =
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent.to_i) ||
+ Fabricate(:ai_agent, id: SiteSetting.ai_image_caption_agent.to_i)
+ caption_agent.update!(enabled: true, vision_enabled: true, default_llm_id: llm_model.id)
+ end
+
it "omits generated descriptions from topic feeds", :aggregate_failures do
description = "A generated RSS-only 字 description"
- AiPostImageDescription.upsert_all(
+ AiPostImageCaption.upsert_all(
[
{
post_id: post.id,
@@ -34,7 +44,7 @@ describe "AI post image descriptions in RSS" do
attempts: 0,
},
],
- unique_by: DiscourseAi::PostImageDescriptions::LOOKUP_INDEX,
+ unique_by: DiscourseAi::PostImageCaptions::LOOKUP_INDEX,
)
processor = CookedPostProcessor.new(post)
diff --git a/plugins/discourse-ai/spec/services/problem_check/ai_image_caption_agent_spec.rb b/plugins/discourse-ai/spec/services/problem_check/ai_image_caption_agent_spec.rb
new file mode 100644
index 00000000000..661d8b22704
--- /dev/null
+++ b/plugins/discourse-ai/spec/services/problem_check/ai_image_caption_agent_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+describe ProblemCheck::AiImageCaptionAgent do
+ subject(:check) { described_class.new }
+
+ fab!(:vision_llm) do
+ Fabricate(:llm_model, display_name: "Vision model", name: "vision-model", vision_enabled: true)
+ end
+ fab!(:text_llm) do
+ Fabricate(:llm_model, display_name: "Text model", name: "text-model", vision_enabled: false)
+ end
+
+ before do
+ SiteSetting.remove_override!(:ai_image_caption_agent)
+ SiteSetting.refresh!
+ enable_current_plugin
+ caption_agent.update!(enabled: true, vision_enabled: true, default_llm_id: vision_llm.id)
+ SiteSetting.ai_post_image_captions_enabled = true
+ end
+
+ def caption_agent
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent.to_i) ||
+ Fabricate(:ai_agent, id: SiteSetting.ai_image_caption_agent.to_i)
+ end
+
+ it "returns no problem when post image captions are disabled" do
+ SiteSetting.ai_post_image_captions_enabled = false
+ caption_agent.update!(enabled: false)
+
+ expect(check).to be_chill_about_it
+ end
+
+ it "returns no problem when discourse AI is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+ caption_agent.update!(enabled: false)
+
+ expect(check).to be_chill_about_it
+ end
+
+ it "returns no problem when the selected caption agent can generate image captions" do
+ expect(check).to be_chill_about_it
+ end
+
+ it "returns no problem when the selected caption agent is disabled for AI bot" do
+ caption_agent.update!(enabled: false)
+
+ expect(check).to be_chill_about_it
+ end
+
+ it "returns a problem when the selected caption agent cannot include images" do
+ caption_agent.update!(vision_enabled: false)
+
+ result = check.call
+
+ expect(result).to have_attributes(priority: "high", target: caption_agent.id)
+ expect(result.message).to include("the agent cannot include image uploads")
+ end
+
+ it "returns a problem when the selected caption agent resolves to a missing LLM" do
+ caption_agent.update!(default_llm_id: -99_999)
+
+ result = check.call
+
+ expect(result).to have_attributes(priority: "high", target: caption_agent.id)
+ expect(result.message).to include("the agent does not resolve to an LLM")
+ end
+
+ it "returns a problem when the selected caption agent resolves to an LLM without image input" do
+ caption_agent.update!(default_llm_id: text_llm.id)
+
+ result = check.call
+
+ expect(result).to have_attributes(priority: "high", target: caption_agent.id)
+ expect(result.message).to include("the resolved LLM does not support image input")
+ end
+
+ it "returns a problem when the selected caption agent does not exist" do
+ SiteSetting.provider.save("ai_image_caption_agent", -99_999, SiteSetting.types[:enum])
+ SiteSetting.refresh!
+
+ result = check.call
+
+ expect(result).to have_attributes(priority: "high", target: -99_999)
+ expect(result.message).to include("the selected agent does not exist")
+ end
+end
diff --git a/plugins/discourse-ai/spec/system/edit_post_image_descriptions_spec.rb b/plugins/discourse-ai/spec/system/edit_post_image_captions_spec.rb
similarity index 76%
rename from plugins/discourse-ai/spec/system/edit_post_image_descriptions_spec.rb
rename to plugins/discourse-ai/spec/system/edit_post_image_captions_spec.rb
index 5c0609d7a89..522fba04339 100644
--- a/plugins/discourse-ai/spec/system/edit_post_image_descriptions_spec.rb
+++ b/plugins/discourse-ai/spec/system/edit_post_image_captions_spec.rb
@@ -1,6 +1,6 @@
# frozen_string_literal: true
-describe "Edit AI post image descriptions" do
+describe "Edit AI post image captions" do
fab!(:admin)
fab!(:first_cat_upload) { create_image_upload("100x100.jpg", "first-cat.jpg") }
fab!(:second_cat_upload) do
@@ -59,7 +59,7 @@ describe "Edit AI post image descriptions" do
let(:topic_page) { PageObjects::Pages::Topic.new }
let(:composer) { PageObjects::Components::Composer.new }
- let(:captions) { PageObjects::Components::AiPostImageDescriptions.new }
+ let(:captions) { PageObjects::Components::AiPostImageCaptions.new }
let(:first_cat_caption) { "An old caption for the first cat" }
let(:second_cat_caption) { "An old caption for the shared second cat" }
@@ -73,7 +73,8 @@ describe "Edit AI post image descriptions" do
before do
enable_current_plugin
SiteSetting.default_locale = "en"
- SiteSetting.ai_post_image_descriptions_enabled = true
+ configure_valid_caption_agent
+ SiteSetting.ai_post_image_captions_enabled = true
SearchIndexer.enable
prepare_post(first_post)
@@ -94,39 +95,27 @@ describe "Edit AI post image descriptions" do
expect(captions).to have_post_image_count(first_post, count: 0)
expect(captions).to have_post_image_count(second_post, count: 2)
expect(captions).to have_post_image_count(third_post, count: 1)
- expect(captions).to have_image_description(
- second_post,
- image: 2,
- description: second_cat_caption,
- )
- expect(captions).to have_image_description(
- third_post,
- image: 1,
- description: second_cat_caption,
- )
+ expect(captions).to have_image_caption(second_post, image: 2, description: second_cat_caption)
+ expect(captions).to have_image_caption(third_post, image: 1, description: second_cat_caption)
topic_page.expand_post_actions(second_post)
topic_page.click_post_action_button(second_post, :edit)
expect(composer).to be_opened
expect(captions).to have_editor_button_count(count: 2)
- captions.edit_preview_image_description(image: 2, description: edited_second_cat_caption)
+ captions.edit_preview_image_caption(image: 2, description: edited_second_cat_caption)
process_description_cooked(post_id: second_post.id, locale: "en")
composer.close
expect(composer).to be_closed
topic_page.visit_topic(cat_topic)
- expect(captions).to have_image_description(
+ expect(captions).to have_image_caption(
second_post,
image: 2,
description: edited_second_cat_caption,
)
- expect(captions).to have_image_description(
- third_post,
- image: 1,
- description: second_cat_caption,
- )
+ expect(captions).to have_image_caption(third_post, image: 1, description: second_cat_caption)
end
it "shows locale-specific captions and original-locale fallback", :aggregate_failures do
@@ -139,19 +128,14 @@ describe "Edit AI post image descriptions" do
Fabricate(:topic_localization, topic: cat_topic, locale: "ja", fancy_title: "猫についての話題")
create_japanese_localization(second_post)
seed_english_descriptions
- seed_image_description(second_post, first_cat_upload, japanese_first_cat_caption, locale: "ja")
- seed_image_description(
- second_post,
- second_cat_upload,
- japanese_second_cat_caption,
- locale: "ja",
- )
+ seed_image_caption(second_post, first_cat_upload, japanese_first_cat_caption, locale: "ja")
+ seed_image_caption(second_post, second_cat_upload, japanese_second_cat_caption, locale: "ja")
process_description_cooked(post_id: second_post.id, locale: "ja")
sign_in(admin)
topic_page.visit_topic(cat_topic)
- expect(captions).to have_image_description(
+ expect(captions).to have_image_caption(
second_post,
image: 2,
description: japanese_second_cat_caption,
@@ -160,11 +144,7 @@ describe "Edit AI post image descriptions" do
admin.user_option.update!(show_original_content: true)
topic_page.visit_topic(cat_topic)
- expect(captions).to have_image_description(
- second_post,
- image: 2,
- description: second_cat_caption,
- )
+ expect(captions).to have_image_caption(second_post, image: 2, description: second_cat_caption)
end
def create_image_upload(filename, original_filename)
@@ -184,19 +164,28 @@ describe "Edit AI post image descriptions" do
post.update_column(:image_upload_id, image_upload.id) if image_upload
end
+ def configure_valid_caption_agent
+ llm_model = assign_fake_provider_to(:ai_default_llm_model)
+ llm_model.update!(vision_enabled: true)
+ caption_agent =
+ AiAgent.find_by(id: SiteSetting.ai_image_caption_agent.to_i) ||
+ Fabricate(:ai_agent, id: SiteSetting.ai_image_caption_agent.to_i)
+ caption_agent.update!(enabled: true, vision_enabled: true, default_llm_id: llm_model.id)
+ end
+
def seed_english_descriptions
- seed_image_description(second_post, first_cat_upload, first_cat_caption)
- seed_image_description(second_post, second_cat_upload, second_cat_caption)
- seed_image_description(third_post, second_cat_upload, second_cat_caption)
- seed_image_description(other_post, dog_upload, dog_caption)
+ seed_image_caption(second_post, first_cat_upload, first_cat_caption)
+ seed_image_caption(second_post, second_cat_upload, second_cat_caption)
+ seed_image_caption(third_post, second_cat_upload, second_cat_caption)
+ seed_image_caption(other_post, dog_upload, dog_caption)
process_description_cooked(post_id: second_post.id, locale: "en")
process_description_cooked(post_id: third_post.id, locale: "en")
process_description_cooked(post_id: other_post.id, locale: "en")
end
- def seed_image_description(post, upload, description, locale: "en")
- AiPostImageDescription.create!(
+ def seed_image_caption(post, upload, description, locale: "en")
+ AiPostImageCaption.create!(
post_id: post.id,
upload_id: upload.id,
base62_sha1: upload.base62_sha1,
@@ -223,9 +212,9 @@ describe "Edit AI post image descriptions" do
def process_description_cooked(post_id:, locale:)
post = Post.find(post_id)
- locale = locale.presence || DiscourseAi::PostImageDescriptions.original_locale(post)
+ locale = locale.presence || DiscourseAi::PostImageCaptions.original_locale(post)
- if locale == DiscourseAi::PostImageDescriptions.original_locale(post)
+ if locale == DiscourseAi::PostImageCaptions.original_locale(post)
Jobs::ProcessPost.new.execute(post_id: post.id, bypass_bump: true)
else
PostLocalization
diff --git a/plugins/discourse-ai/spec/system/page_objects/components/ai_post_image_descriptions.rb b/plugins/discourse-ai/spec/system/page_objects/components/ai_post_image_captions.rb
similarity index 81%
rename from plugins/discourse-ai/spec/system/page_objects/components/ai_post_image_descriptions.rb
rename to plugins/discourse-ai/spec/system/page_objects/components/ai_post_image_captions.rb
index 69e5ca72c14..19d4755f30a 100644
--- a/plugins/discourse-ai/spec/system/page_objects/components/ai_post_image_descriptions.rb
+++ b/plugins/discourse-ai/spec/system/page_objects/components/ai_post_image_captions.rb
@@ -2,15 +2,15 @@
module PageObjects
module Components
- class AiPostImageDescriptions < PageObjects::Components::Base
- PREVIEW_EDITOR_BUTTON = ".d-editor-preview .ai-post-image-description-editor__button"
- MODAL = ".ai-post-image-description-editor-modal"
+ class AiPostImageCaptions < PageObjects::Components::Base
+ PREVIEW_EDITOR_BUTTON = ".d-editor-preview .ai-post-image-caption-editor__button"
+ MODAL = ".ai-post-image-caption-editor-modal"
def has_post_image_count?(post, count:)
post_component(post).cooked_content.has_css?("img", count: count, visible: :all)
end
- def has_image_description?(post, image:, description:)
+ def has_image_caption?(post, image:, description:)
post_component(post).cooked_content.has_xpath?(
"(.//img)[#{image}][contains(@aria-description, #{xpath_literal(description)})]",
visible: :all,
@@ -21,7 +21,7 @@ module PageObjects
has_css?(PREVIEW_EDITOR_BUTTON, count: count)
end
- def edit_preview_image_description(image:, description:)
+ def edit_preview_image_caption(image:, description:)
all(PREVIEW_EDITOR_BUTTON)[image - 1].click
find("#{MODAL} textarea").fill_in(with: description)
find("#{MODAL} .btn-primary").click
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-post-image-description-editor-button-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-post-image-caption-editor-button-test.gjs
similarity index 63%
rename from plugins/discourse-ai/test/javascripts/integration/components/ai-post-image-description-editor-button-test.gjs
rename to plugins/discourse-ai/test/javascripts/integration/components/ai-post-image-caption-editor-button-test.gjs
index c792c52364e..32b4af9b1c1 100644
--- a/plugins/discourse-ai/test/javascripts/integration/components/ai-post-image-description-editor-button-test.gjs
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-post-image-caption-editor-button-test.gjs
@@ -2,12 +2,12 @@ import Service from "@ember/service";
import { click, render } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import AiPostImageDescriptionEditorButton from "discourse/plugins/discourse-ai/discourse/components/ai-post-image-description-editor-button";
+import AiPostImageCaptionEditorButton from "discourse/plugins/discourse-ai/discourse/components/ai-post-image-caption-editor-button";
-class PostImageDescriptionEditorStub extends Service {
+class PostImageCaptionEditorStub extends Service {
openedBase62Sha1 = null;
- descriptionFor(base62Sha1) {
+ captionFor(base62Sha1) {
if (base62Sha1 === "abc123") {
return "A stored description";
}
@@ -21,16 +21,16 @@ class ModalStub extends Service {
}
module(
- "Integration | Component | AiPostImageDescriptionEditorButton",
+ "Integration | Component | AiPostImageCaptionEditorButton",
function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.owner.unregister("service:post-image-description-editor");
+ this.owner.unregister("service:post-image-caption-editor");
this.owner.unregister("service:modal");
this.owner.register(
- "service:post-image-description-editor",
- PostImageDescriptionEditorStub
+ "service:post-image-caption-editor",
+ PostImageCaptionEditorStub
);
this.owner.register("service:modal", ModalStub);
});
@@ -38,23 +38,23 @@ module(
test("renders when the image has an editable description", async function (assert) {
await render(
<template>
- <AiPostImageDescriptionEditorButton @base62Sha1="abc123" />
+ <AiPostImageCaptionEditorButton @base62Sha1="abc123" />
</template>
);
assert
- .dom(".ai-post-image-description-editor__button")
+ .dom(".ai-post-image-caption-editor__button")
.exists("the edit button is shown");
});
test("opens the editor modal for the image", async function (assert) {
await render(
<template>
- <AiPostImageDescriptionEditorButton @base62Sha1="abc123" />
+ <AiPostImageCaptionEditorButton @base62Sha1="abc123" />
</template>
);
- await click(".ai-post-image-description-editor__button");
+ await click(".ai-post-image-caption-editor__button");
const modal = this.owner.lookup("service:modal");
assert.deepEqual(modal.model, {
@@ -66,12 +66,12 @@ module(
test("does not render without an editable description", async function (assert) {
await render(
<template>
- <AiPostImageDescriptionEditorButton @base62Sha1="missing" />
+ <AiPostImageCaptionEditorButton @base62Sha1="missing" />
</template>
);
assert
- .dom(".ai-post-image-description-editor__button")
+ .dom(".ai-post-image-caption-editor__button")
.doesNotExist("the edit button is hidden");
});
}
diff --git a/plugins/discourse-ai/test/javascripts/unit/lib/ai-feature-setting-groups-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/ai-feature-setting-groups-test.js
index 578123a7db0..8c74aec4771 100644
--- a/plugins/discourse-ai/test/javascripts/unit/lib/ai-feature-setting-groups-test.js
+++ b/plugins/discourse-ai/test/javascripts/unit/lib/ai-feature-setting-groups-test.js
@@ -38,6 +38,28 @@ module("Unit | Lib | ai-feature-setting-groups", function () {
"settings",
"first group should be settings"
);
+ assert.false(
+ groups.some((group) => group.settings.includes("ai_image_caption_agent")),
+ "bot should not include the image caption agent"
+ );
+ });
+
+ test("returns correct groups for image caption", function (assert) {
+ const groups = getSettingGroupsForFeature("image_caption");
+
+ assert.strictEqual(groups.length, 1, "image caption should have 1 group");
+ assert.strictEqual(
+ groups[0].key,
+ "settings",
+ "first group should be settings"
+ );
+ assert.deepEqual(groups[0].settings, [
+ "ai_post_image_captions_enabled",
+ "ai_image_caption_agent",
+ "ai_post_image_captions_per_post_limit",
+ "ai_post_image_captions_backfill_hourly_rate",
+ "ai_post_image_captions_backfill_max_age_days",
+ ]);
});
test("returns correct groups for summarization", function (assert) {
diff --git a/plugins/discourse-ai/test/javascripts/unit/lib/post-image-description-editor-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/post-image-caption-editor-test.js
similarity index 91%
rename from plugins/discourse-ai/test/javascripts/unit/lib/post-image-description-editor-test.js
rename to plugins/discourse-ai/test/javascripts/unit/lib/post-image-caption-editor-test.js
index 79d79c45717..7fb273d14ab 100644
--- a/plugins/discourse-ai/test/javascripts/unit/lib/post-image-description-editor-test.js
+++ b/plugins/discourse-ai/test/javascripts/unit/lib/post-image-caption-editor-test.js
@@ -1,7 +1,7 @@
import { module, test } from "qunit";
-import { imageBase62Sha1 } from "discourse/plugins/discourse-ai/discourse/lib/post-image-description-editor";
+import { imageBase62Sha1 } from "discourse/plugins/discourse-ai/discourse/lib/post-image-caption-editor";
-module("Unit | Lib | post-image-description-editor", function () {
+module("Unit | Lib | post-image-caption-editor", function () {
test("imageBase62Sha1 reads data-base62-sha1", function (assert) {
const image = document.createElement("img");
image.dataset.base62Sha1 = "abc123XYZ";
diff --git a/plugins/discourse-ai/test/javascripts/unit/services/post-image-caption-editor-test.js b/plugins/discourse-ai/test/javascripts/unit/services/post-image-caption-editor-test.js
new file mode 100644
index 00000000000..2c381b7e51b
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/unit/services/post-image-caption-editor-test.js
@@ -0,0 +1,86 @@
+import { getOwner } from "@ember/owner";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { EDIT } from "discourse/models/composer";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+
+module("Unit | Service | post-image-caption-editor", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ const owner = getOwner(this);
+ const composer = owner.lookup("service:composer");
+ composer.model = {
+ action: EDIT,
+ locale: "ja",
+ post: { id: 42 },
+ };
+
+ owner.lookup("service:site-settings").ai_post_image_captions_enabled = true;
+
+ const service = owner.lookup("service:post-image-caption-editor");
+ service.captions = new Map();
+ service.loadedKey = null;
+ service.loadingKey = null;
+ });
+
+ test("ensureLoaded fetches captions for the edited post", async function (assert) {
+ pretender.get("/discourse-ai/post-image-captions/:post_id", (request) => {
+ assert.strictEqual(request.params.post_id, "42");
+ assert.strictEqual(request.queryParams.locale, "ja");
+
+ return response({
+ captions: [
+ { base62_sha1: "abc123", description: "A stored description" },
+ ],
+ });
+ });
+
+ const service = getOwner(this).lookup("service:post-image-caption-editor");
+
+ await service.ensureLoaded();
+
+ assert.strictEqual(service.captionFor("abc123"), "A stored description");
+ });
+
+ test("ensureLoaded skips non-edit composers", async function (assert) {
+ let requestCount = 0;
+ pretender.get("/discourse-ai/post-image-captions/:post_id", () => {
+ requestCount += 1;
+ return response({ captions: [] });
+ });
+
+ const composer = getOwner(this).lookup("service:composer");
+ composer.model.action = "reply";
+
+ const service = getOwner(this).lookup("service:post-image-caption-editor");
+
+ await service.ensureLoaded();
+
+ assert.strictEqual(requestCount, 0);
+ });
+
+ test("save updates the local caption", async function (assert) {
+ pretender.put(
+ "/discourse-ai/post-image-captions/:post_id/:base62_sha1",
+ (request) => {
+ assert.strictEqual(request.params.post_id, "42");
+ assert.strictEqual(request.params.base62_sha1, "abc123");
+
+ const params = new URLSearchParams(request.requestBody);
+ assert.strictEqual(params.get("locale"), "ja");
+
+ return response({
+ base62_sha1: "abc123",
+ description: "An edited description",
+ });
+ }
+ );
+
+ const service = getOwner(this).lookup("service:post-image-caption-editor");
+
+ await service.save("abc123", "An edited description");
+
+ assert.strictEqual(service.captionFor("abc123"), "An edited description");
+ });
+});
diff --git a/plugins/discourse-ai/test/javascripts/unit/services/post-image-description-editor-test.js b/plugins/discourse-ai/test/javascripts/unit/services/post-image-description-editor-test.js
deleted file mode 100644
index 85027b93a83..00000000000
--- a/plugins/discourse-ai/test/javascripts/unit/services/post-image-description-editor-test.js
+++ /dev/null
@@ -1,102 +0,0 @@
-import { getOwner } from "@ember/owner";
-import { setupTest } from "ember-qunit";
-import { module, test } from "qunit";
-import { EDIT } from "discourse/models/composer";
-import pretender, { response } from "discourse/tests/helpers/create-pretender";
-
-module("Unit | Service | post-image-description-editor", function (hooks) {
- setupTest(hooks);
-
- hooks.beforeEach(function () {
- const owner = getOwner(this);
- const composer = owner.lookup("service:composer");
- composer.model = {
- action: EDIT,
- locale: "ja",
- post: { id: 42 },
- };
-
- owner.lookup("service:site-settings").ai_post_image_descriptions_enabled =
- true;
-
- const service = owner.lookup("service:post-image-description-editor");
- service.descriptions = new Map();
- service.loadedKey = null;
- service.loadingKey = null;
- });
-
- test("ensureLoaded fetches descriptions for the edited post", async function (assert) {
- pretender.get(
- "/discourse-ai/post-image-descriptions/:post_id",
- (request) => {
- assert.strictEqual(request.params.post_id, "42");
- assert.strictEqual(request.queryParams.locale, "ja");
-
- return response({
- descriptions: [
- { base62_sha1: "abc123", description: "A stored description" },
- ],
- });
- }
- );
-
- const service = getOwner(this).lookup(
- "service:post-image-description-editor"
- );
-
- await service.ensureLoaded();
-
- assert.strictEqual(
- service.descriptionFor("abc123"),
- "A stored description"
- );
- });
-
- test("ensureLoaded skips non-edit composers", async function (assert) {
- let requestCount = 0;
- pretender.get("/discourse-ai/post-image-descriptions/:post_id", () => {
- requestCount += 1;
- return response({ descriptions: [] });
- });
-
- const composer = getOwner(this).lookup("service:composer");
- composer.model.action = "reply";
-
- const service = getOwner(this).lookup(
- "service:post-image-description-editor"
- );
-
- await service.ensureLoaded();
-
- assert.strictEqual(requestCount, 0);
- });
-
- test("save updates the local description", async function (assert) {
- pretender.put(
- "/discourse-ai/post-image-descriptions/:post_id/:base62_sha1",
- (request) => {
- assert.strictEqual(request.params.post_id, "42");
- assert.strictEqual(request.params.base62_sha1, "abc123");
-
- const params = new URLSearchParams(request.requestBody);
- assert.strictEqual(params.get("locale"), "ja");
-
- return response({
- base62_sha1: "abc123",
- description: "An edited description",
- });
- }
- );
-
- const service = getOwner(this).lookup(
- "service:post-image-description-editor"
- );
-
- await service.save("abc123", "An edited description");
-
- assert.strictEqual(
- service.descriptionFor("abc123"),
- "An edited description"
- );
- });
-});