A platform for community discussion. Free, open, simple.
FEATURE: Share AI artifacts and conversations (#44396)
Samb28f2a44c410
diff --git a/db/structure.sql b/db/structure.sqlindex a192b8347e8..9114f28b1b5 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -641,6 +641,79 @@ CREATE SEQUENCE public.ai_artifact_key_values_id_seqALTER SEQUENCE public.ai_artifact_key_values_id_seq OWNED BY public.ai_artifact_key_values.id;+--+-- Name: ai_artifact_share_key_values; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.ai_artifact_share_key_values (+ id bigint NOT NULL,+ ai_artifact_share_id bigint NOT NULL,+ user_id integer NOT NULL,+ key character varying(50) NOT NULL,+ value character varying(20000) NOT NULL,+ public boolean DEFAULT false NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: ai_artifact_share_key_values_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.ai_artifact_share_key_values_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: ai_artifact_share_key_values_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.ai_artifact_share_key_values_id_seq OWNED BY public.ai_artifact_share_key_values.id;+++--+-- Name: ai_artifact_shares; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.ai_artifact_shares (+ id bigint NOT NULL,+ ai_artifact_id bigint NOT NULL,+ user_id integer NOT NULL,+ share_key character varying NOT NULL,+ name character varying NOT NULL,+ version_number integer DEFAULT 0 NOT NULL,+ html character varying(65535),+ css character varying(65535),+ js character varying(65535),+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: ai_artifact_shares_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.ai_artifact_shares_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: ai_artifact_shares_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.ai_artifact_shares_id_seq OWNED BY public.ai_artifact_shares.id;++---- Name: ai_artifact_versions; Type: TABLE; Schema: public; Owner: ---@@ -13854,6 +13927,20 @@ ALTER TABLE ONLY public.ai_api_request_stats ALTER COLUMN id SET DEFAULT nextvalALTER TABLE ONLY public.ai_artifact_key_values ALTER COLUMN id SET DEFAULT nextval('public.ai_artifact_key_values_id_seq'::regclass);+--+-- Name: ai_artifact_share_key_values id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.ai_artifact_share_key_values ALTER COLUMN id SET DEFAULT nextval('public.ai_artifact_share_key_values_id_seq'::regclass);+++--+-- Name: ai_artifact_shares id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.ai_artifact_shares ALTER COLUMN id SET DEFAULT nextval('public.ai_artifact_shares_id_seq'::regclass);++---- Name: ai_artifact_versions id; Type: DEFAULT; Schema: public; Owner: ---@@ -16336,6 +16423,22 @@ ALTER TABLE ONLY public.ai_artifact_key_valuesADD CONSTRAINT ai_artifact_key_values_pkey PRIMARY KEY (id);+--+-- Name: ai_artifact_share_key_values ai_artifact_share_key_values_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.ai_artifact_share_key_values+ ADD CONSTRAINT ai_artifact_share_key_values_pkey PRIMARY KEY (id);+++--+-- Name: ai_artifact_shares ai_artifact_shares_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.ai_artifact_shares+ ADD CONSTRAINT ai_artifact_shares_pkey PRIMARY KEY (id);++---- Name: ai_artifact_versions ai_artifact_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -20561,6 +20664,48 @@ CREATE INDEX index_ai_api_request_stats_on_created_at_and_user_id ON public.ai_aCREATE UNIQUE INDEX index_ai_artifact_kv_unique ON public.ai_artifact_key_values USING btree (ai_artifact_id, user_id, key);+--+-- Name: index_ai_artifact_share_key_values_on_user_id; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_ai_artifact_share_key_values_on_user_id ON public.ai_artifact_share_key_values USING btree (user_id);+++--+-- Name: index_ai_artifact_share_kv_unique; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_ai_artifact_share_kv_unique ON public.ai_artifact_share_key_values USING btree (ai_artifact_share_id, user_id, key);+++--+-- Name: index_ai_artifact_shares_on_ai_artifact_id; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_ai_artifact_shares_on_ai_artifact_id ON public.ai_artifact_shares USING btree (ai_artifact_id);+++--+-- Name: index_ai_artifact_shares_on_share_key; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_ai_artifact_shares_on_share_key ON public.ai_artifact_shares USING btree (share_key);+++--+-- Name: index_ai_artifact_shares_on_user_id_and_ai_artifact_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_ai_artifact_shares_on_user_id_and_ai_artifact_id ON public.ai_artifact_shares USING btree (user_id, ai_artifact_id);+++--+-- Name: index_ai_artifact_shares_on_user_id_and_created_at; Type: INDEX; Schema: public; Owner: -+--++CREATE INDEX index_ai_artifact_shares_on_user_id_and_created_at ON public.ai_artifact_shares USING btree (user_id, created_at);++---- Name: index_ai_artifact_versions_on_ai_artifact_id_and_version_number; Type: INDEX; Schema: public; Owner: ---@@ -25593,6 +25738,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20261009144947'),('20261009130230'),('20261009121104'),+('20261008005940'),('20261007082151'),('20261006113418'),('20261005091527'),@@ -25606,6 +25752,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260923141924'),('20260923080644'),('20260923080642'),+('20260922233925'),('20260922233816'),('20260921120000'),('20260921081150'),diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_key_values_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_key_values_controller.rbindex d714003ec11..41f8848e875 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_key_values_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_key_values_controller.rb@@ -92,7 +92,7 @@ module DiscourseAiquery = @artifact.key_valuesquery =- if current_user&.admin?+ if can_read_all_private_key_values?queryelsif current_userquery.where("user_id = ? OR public = true", current_user.id)@@ -113,6 +113,10 @@ module DiscourseAiqueryend+ def can_read_all_private_key_values?+ current_user&.admin?+ end+def find_artifact@artifact = AiArtifact.find_by(id: params[:artifact_id])raise Discourse::NotFound if !@artifactdiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_share_key_values_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_share_key_values_controller.rbnew file mode 100644index 00000000000..8327e55c474--- /dev/null+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_share_key_values_controller.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ArtifactShareKeyValuesController < ArtifactKeyValuesController+ def set+ @artifact.with_lock { super }+ end++ private++ def can_read_all_private_key_values?+ false+ end++ def find_artifact+ @artifact = AiArtifactShare.find_by(share_key: params[:share_key])+ raise Discourse::NotFound if !@artifact&.publicly_visible?+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_shares_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_shares_controller.rbnew file mode 100644index 00000000000..c49b19d0c4e--- /dev/null+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifact_shares_controller.rb@@ -0,0 +1,143 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ArtifactSharesController < ::ApplicationController+ requires_plugin PLUGIN_NAME+ requires_login+ before_action :require_artifacts!, only: %i[eligibility create update]+ before_action :require_management!, only: %i[index destroy]++ def eligibility+ artifact = AiArtifact.find_by(id: params[:id])+ can_share = eligible?(artifact)+ share = AiArtifactShare.find_by(ai_artifact: artifact, user: current_user) if can_share+ render json: {+ can_share: can_share,+ share:+ share &&+ { share_key: share.share_key, url: share.url, version: share.version_number },+ }+ end++ def index+ render json:+ ArtifactSharesQuery.new(+ user: current_user,+ type: params[:type],+ order: params[:order],+ cursor: params[:cursor],+ ).call+ end++ def create+ artifact = AiArtifact.find_by(id: params[:id])+ raise Discourse::NotFound if !eligible?(artifact)++ RateLimiter.new(current_user, "share-ai-artifact", 10, 1.minute).performed!+ version = requested_version(artifact)+ share = AiArtifactShare.find_by(ai_artifact: artifact, user: current_user)+ return render_share(share, version: version) if share++ snapshot =+ AiArtifactShare.new(ai_artifact: artifact, user: current_user).snapshot_attributes(+ version_number: version,+ )+ inserted =+ AiArtifactShare.insert_all(+ [+ snapshot.merge(+ ai_artifact_id: artifact.id,+ user_id: current_user.id,+ share_key: SecureRandom.urlsafe_base64(32),+ ),+ ],+ unique_by: :index_ai_artifact_shares_on_user_id_and_ai_artifact_id,+ )+ share = AiArtifactShare.find_by!(ai_artifact: artifact, user: current_user)+ return render_share(share, version: version) if inserted.rows.empty?++ render json: {+ share_key: share.share_key,+ url: share.url,+ version: share.version_number,+ },+ status: :created+ rescue ActiveRecord::RecordNotUnique+ render_share(+ AiArtifactShare.find_by!(ai_artifact: artifact, user: current_user),+ version: version,+ )+ end++ def update+ share = owned_share+ raise Discourse::NotFound if !eligible?(share.ai_artifact)++ RateLimiter.new(current_user, "share-ai-artifact", 10, 1.minute).performed!+ version = requested_version(share.ai_artifact)+ share.pin!(version_number: version)+ render json: { share_key: share.share_key, url: share.url, version: share.version_number }+ end++ def destroy+ owned_share.destroy!+ head :no_content+ end++ private++ def owned_share+ AiArtifactShare.where(user: current_user).find_by!(share_key: params[:share_key])+ end++ def render_share(share, version:)+ if share.version_number != version+ message = I18n.t("discourse_ai.ai_artifact.share_version_conflict")+ return render json: { error: message, errors: [message] }, status: :conflict+ end++ render json: { share_key: share.share_key, url: share.url, version: share.version_number }+ end++ def eligible?(artifact)+ return false if !artifact++ post = artifact.post+ topic = post&.topic+ if !post || post.deleted_at || !topic || topic.deleted_at || !guardian.can_see?(post)+ return false+ end+ return false if !guardian.can_share_ai_bot_conversation?(topic)++ artifact.user_id == current_user.id ||+ (+ topic.user_id == current_user.id &&+ DiscourseAi::AiBot::EntryPoint.all_bot_ids.include?(artifact.user_id)+ )+ end++ def requested_version(artifact)+ raise Discourse::NotFound if !params[:version].to_s.match?(/\A(?:0|[1-9]\d*)\z/)++ version = params[:version].to_i+ if version != 0 && !artifact.versions.exists?(version_number: version)+ raise Discourse::NotFound+ end++ version+ end++ def require_management!+ raise Discourse::NotFound if !SiteSetting.discourse_ai_enabled+ end++ def require_artifacts!+ if !SiteSetting.discourse_ai_enabled ||+ !SiteSetting.ai_artifact_security.in?(%w[lax hybrid strict])+ raise Discourse::NotFound+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifacts_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifacts_controller.rbindex 21e549b0410..d481ac9cdf5 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifacts_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/artifacts_controller.rb@@ -6,8 +6,79 @@ module DiscourseAirequires_plugin PLUGIN_NAMEbefore_action :require_site_settings!- skip_before_action :preload_json, :check_xhr, only: %i[show]- skip_after_action :set_cross_origin_opener_policy_header, only: %i[show]+ skip_before_action :preload_json, :check_xhr, only: %i[show shared embed forum]+ skip_after_action :set_cross_origin_opener_policy_header, only: %i[show shared embed forum]++ def embed+ raise Discourse::NotFound if !params[:id].to_s.match?(/\A[1-9]\d*\z/)++ artifact = AiArtifact.find(params[:id])+ raise Discourse::NotFound if !artifact.publicly_embeddable?++ version = nil+ if params[:version].present?+ raise Discourse::NotFound if !params[:version].to_s.match?(/\A[1-9]\d*\z/)++ version = artifact.versions.find_by(version_number: params[:version])+ raise Discourse::NotFound if !version+ end++ untrusted_html = build_untrusted_html(version || artifact, artifact.name, standalone: true)+ trusted_html = build_trusted_html(nil, nil, artifact.name, untrusted_html, standalone: true)++ set_security_headers+ response.headers["Referrer-Policy"] = "no-referrer"+ response.headers["Cache-Control"] = "no-store"+ render html: trusted_html.html_safe, layout: false, content_type: "text/html"+ end++ def shared+ share = find_public_share+ untrusted_html = build_untrusted_html(share, share.name, standalone: true)+ trusted_html = build_trusted_html(nil, nil, share.name, untrusted_html, standalone: true)++ set_security_headers+ response.headers["Referrer-Policy"] = "no-referrer"+ response.headers["Cache-Control"] = "no-store"+ render html: trusted_html.html_safe, layout: false, content_type: "text/html"+ end++ def forum+ share = find_public_share+ untrusted_html = build_untrusted_html(share, share.name)+ trusted_html = build_trusted_html(share, nil, share.name, untrusted_html)++ set_native_security_headers+ response.headers["Referrer-Policy"] = "no-referrer"+ response.headers["Cache-Control"] = "no-store"+ render html: trusted_html.html_safe, layout: false, content_type: "text/html"+ end++ def shared_metadata+ render_metadata(find_public_share.name)+ end++ def metadata+ id = params[:id].to_s+ if !id.match?(/\A[1-9]\d{0,18}\z/) || id.to_i > 9_223_372_036_854_775_807+ raise Discourse::NotFound+ end++ artifact = AiArtifact.find_by(id: id)+ raise Discourse::NotFound if !artifact&.available_to?(guardian)++ if params.key?(:version)+ version = params[:version].to_s+ if !version.match?(/\A(?:0|[1-9]\d{0,9})\z/) || version.to_i > 2_147_483_647+ raise Discourse::NotFound+ end+ if version != "0" && !artifact.versions.exists?(version_number: version.to_i)+ raise Discourse::NotFound+ end+ end++ render_metadata(artifact.name)+ enddef showartifact = AiArtifact.find(params[:id])@@ -25,13 +96,26 @@ module DiscourseAiuntrusted_html = build_untrusted_html(artifact_version || artifact, name)trusted_html = build_trusted_html(artifact, artifact_version, name, untrusted_html)- set_security_headers+ set_native_security_headersrender html: trusted_html.html_safe, layout: false, content_type: "text/html"endprivate- def build_untrusted_html(artifact, name)+ def render_metadata(name)+ response.headers["Cache-Control"] = "no-store"+ response.headers["X-Robots-Tag"] = "noindex"+ render json: { name: name }+ end++ def find_public_share+ share = AiArtifactShare.find_by(share_key: params[:share_key])+ raise Discourse::NotFound if !share&.publicly_visible?++ share+ end++ def build_untrusted_html(artifact, name, standalone: false)js = prepare_javascript(artifact.js)sanitized_css = artifact.css.to_s.gsub(%r{</style}i, '<\/style')@@ -44,7 +128,7 @@ module DiscourseAi<style>#{sanitized_css}</style>- #{build_iframe_javascript}+ #{standalone ? build_standalone_javascript : build_iframe_javascript}</head><body>#{artifact.html}@@ -54,7 +138,7 @@ module DiscourseAiHTMLend- def build_trusted_html(artifact, artifact_version, name, untrusted_html)+ def build_trusted_html(artifact, artifact_version, name, untrusted_html, standalone: false)<<~HTML<!DOCTYPE html><html>@@ -62,7 +146,7 @@ module DiscourseAi<meta charset="UTF-8"><title>#{ERB::Util.html_escape(name)}</title><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=yes, viewport-fit=cover, interactive-widget=resizes-content">- <meta name="csrf-token" content="#{form_authenticity_token}">+ #{"<meta name=\"csrf-token\" content=\"#{form_authenticity_token}\">" unless standalone}<style>html, body, iframe {margin: 0;@@ -78,8 +162,8 @@ module DiscourseAi</style></head><body>- <iframe sandbox="allow-scripts allow-forms" height="100%" width="100%" srcdoc="#{ERB::Util.html_escape(untrusted_html)}" frameborder="0"></iframe>- #{build_parent_javascript(artifact)}+ <iframe sandbox="allow-scripts allow-forms" title="#{ERB::Util.html_escape(name)}" height="100%" width="100%" srcdoc="#{ERB::Util.html_escape(untrusted_html)}" frameborder="0"></iframe>+ #{build_parent_javascript(artifact) unless standalone}</body></html>HTML@@ -104,6 +188,21 @@ module DiscourseAi}end+ def build_standalone_javascript+ <<~JAVASCRIPT+ <script>+ window.discourseArtifactData = {};+ window.discourseArtifactReady = Promise.resolve(window.discourseArtifactData);+ window.discourseArtifact = {+ get: function() { return Promise.reject(new Error('Key-value storage is unavailable in public shares')); },+ set: function() { return Promise.reject(new Error('Key-value storage is unavailable in public shares')); },+ delete: function() { return Promise.reject(new Error('Key-value storage is unavailable in public shares')); },+ index: function() { return Promise.reject(new Error('Key-value storage is unavailable in public shares')); }+ };+ </script>+ JAVASCRIPT+ end+def build_iframe_javascript<<~JAVASCRIPT<script>@@ -168,6 +267,13 @@ module DiscourseAienddef build_parent_javascript(artifact)+ storage_url =+ if artifact.is_a?(AiArtifactShare)+ "/discourse-ai/ai-bot/artifact-share-key-values/#{artifact.share_key}.json"+ else+ "/discourse-ai/ai-bot/artifact-key-values/#{artifact.id}.json"+ end+<<~JAVASCRIPT<script>const iframe = document.querySelector('iframe');@@ -191,10 +297,10 @@ module DiscourseAiif (event.data && event.data.type === 'discourse-artifact-kv') {if (event.source !== iframe.contentWindow) return;const { action, data, requestId } = event.data;- const artifactId = #{artifact.id};+ const baseUrl = #{storage_url.to_json};try {- const result = await handleKeyValueRequest(action, data, artifactId);+ const result = await handleKeyValueRequest(action, data, baseUrl);event.source.postMessage({requestId: requestId,result: result@@ -208,8 +314,7 @@ module DiscourseAi}});- async function handleKeyValueRequest(action, data, artifactId) {- const baseUrl = '/discourse-ai/ai-bot/artifact-key-values/' + artifactId + ".json";+ async function handleKeyValueRequest(action, data, baseUrl) {const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';switch (action) {@@ -324,6 +429,12 @@ module DiscourseAiJAVASCRIPTend+ def set_native_security_headers+ set_security_headers+ response.headers["X-Frame-Options"] = "SAMEORIGIN"+ response.headers["Content-Security-Policy"] += " frame-ancestors 'self';"+ end+def set_security_headersresponse.headers.delete("X-Frame-Options")response.headers["Cross-Origin-Opener-Policy"] = "same-origin"diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/shared_ai_conversations_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/shared_ai_conversations_controller.rbindex 75018dd6432..98dc2a77e89 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/shared_ai_conversations_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/shared_ai_conversations_controller.rb@@ -4,12 +4,21 @@ module DiscourseAimodule AiBotclass SharedAiConversationsController < ::ApplicationControllerrequires_plugin PLUGIN_NAME- requires_login only: %i[create destroy preview]+ requires_login only: %i[index create destroy preview]before_action :require_site_settings!skip_before_action :preload_json, :check_xhr, only: %i[show asset]skip_before_action :redirect_to_login_if_required, :verify_authenticity_token, only: %i[asset]+ def index+ render json:+ SharedConversationsQuery.new(+ user: current_user,+ order: params[:order],+ cursor: params[:cursor],+ ).call+ end+def createensure_allowed_create!@@ -89,9 +98,10 @@ module DiscourseAiprivatedef require_site_settings!- if !SiteSetting.discourse_ai_enabled ||- !SiteSetting.ai_bot_public_sharing_allowed_groups_map.any? ||- !SiteSetting.ai_bot_enabled+ raise Discourse::NotFound if !SiteSetting.discourse_ai_enabled+ return if action_name.in?(%w[index destroy])++ if !SiteSetting.ai_bot_public_sharing_allowed_groups_map.any? || !SiteSetting.ai_bot_enabledraise Discourse::NotFoundendenddiff --git a/plugins/discourse-ai/app/models/ai_artifact.rb b/plugins/discourse-ai/app/models/ai_artifact.rbindex fbceccffa7f..14772006c4f 100644--- a/plugins/discourse-ai/app/models/ai_artifact.rb+++ b/plugins/discourse-ai/app/models/ai_artifact.rb@@ -3,6 +3,7 @@class AiArtifact < ActiveRecord::Basehas_many :versions, class_name: "AiArtifactVersion", dependent: :destroyhas_many :key_values, class_name: "AiArtifactKeyValue", dependent: :destroy+ has_many :shares, class_name: "AiArtifactShare", dependent: :destroybelongs_to :userbelongs_to :postvalidates :html, length: { maximum: 65_535 }@@ -48,6 +49,11 @@ class AiArtifact < ActiveRecord::Baseendend+ def self.embed_url(id, version = nil)+ path = "#{Discourse.base_url}/discourse-ai/ai-bot/artifacts/#{id}"+ version ? "#{path}/#{version}/embed" : "#{path}/embed"+ end+def self.share_publicly(id:, post:)artifact = AiArtifact.find_by(id: id)if artifact&.post&.topic&.id == post.topic.id@@ -112,6 +118,23 @@ class AiArtifact < ActiveRecord::Baseguardian.can_see?(source_post)end+ def publicly_embeddable?+ if !SiteSetting.discourse_ai_enabled ||+ !SiteSetting.ai_artifact_security.in?(%w[lax hybrid strict])+ return false+ end++ source_post = Post.find_by(id: post_id)+ topic = source_post&.topic+ return false if !topic || source_post.deleted_at || topic.deleted_at+ return true if Guardian.new(nil).can_see?(source_post)+ return false if !public?++ conversation = SharedAiConversation.find_by(target: topic)+ conversation&.publicly_visible? &&+ conversation.context.any? { |context_post| context_post["id"] == source_post.id }+ end+def public?metadata&.dig("public") == trueenddiff --git a/plugins/discourse-ai/app/models/ai_artifact_share.rb b/plugins/discourse-ai/app/models/ai_artifact_share.rbnew file mode 100644index 00000000000..004e3f6b85b--- /dev/null+++ b/plugins/discourse-ai/app/models/ai_artifact_share.rb@@ -0,0 +1,112 @@+# frozen_string_literal: true++class AiArtifactShare < ActiveRecord::Base+ belongs_to :ai_artifact+ belongs_to :user+ has_many :key_values, class_name: "AiArtifactShareKeyValue", dependent: :destroy++ validates :share_key, presence: true, uniqueness: true+ validates :html, :css, :js, length: { maximum: 65_535 }++ before_validation :generate_share_key, on: :create++ # Snapshots outlive the settings and group membership that allowed publishing,+ # so public visibility is re-evaluated on every read rather than at publish time.+ def self.publicly_viewable_by?(user)+ return false if !SiteSetting.discourse_ai_enabled || !SiteSetting.ai_bot_enabled+ return false if !user++ allowed_group_ids = SiteSetting.ai_bot_public_sharing_allowed_groups_map+ return false if allowed_group_ids.empty?++ user.in_any_groups?(allowed_group_ids)+ end++ def publicly_visible?+ return false if !SiteSetting.ai_artifact_security.in?(%w[lax hybrid strict])+ return false if !self.class.publicly_viewable_by?(User.find_by(id: user_id))++ post = ai_artifact&.post+ topic = post&.topic+ post && !post.deleted_at && topic && !topic.deleted_at+ end++ def url+ "#{Discourse.base_url}/discourse-ai/ai-bot/artifact-shares/#{share_key}"+ end++ def pin!(version_number:)+ update!(snapshot_attributes(version_number: version_number))+ end++ def snapshot_attributes(version_number:)+ source =+ if version_number == 0+ ai_artifact+ else+ ai_artifact.versions.find_by(version_number: version_number)+ end+ raise Discourse::NotFound if !source++ upload_roots =+ if SiteSetting.Upload.enable_s3_uploads+ [SiteSetting.Upload.s3_base_url, SiteSetting.Upload.s3_cdn_url].filter_map do |url|+ url.presence&.sub(/\Ahttps?:/, "")&.sub(%r{/+\z}, "")+ end+ else+ []+ end++ if [source.html, source.css, source.js].any? { |content|+ content = CGI.unescapeHTML(content.to_s)+ content.match?(%r{upload://|/(?:secure-(?:media-)?)?uploads/}i) ||+ upload_roots.any? do |root|+ content.match?(%r{(?:https?:)?#{Regexp.escape(root)}(?:/|[?#])}i)+ end+ }+ raise Discourse::InvalidAccess.new(+ nil,+ nil,+ custom_message: "discourse_ai.ai_artifact.uploads_cannot_be_shared",+ )+ end++ {+ name: ai_artifact.name,+ version_number: version_number,+ html: source.html,+ css: source.css,+ js: source.js,+ }+ end++ private++ def generate_share_key+ self.share_key ||= SecureRandom.urlsafe_base64(32)+ end+end++# == Schema Information+#+# Table name: ai_artifact_shares+#+# id :bigint not null, primary key+# css :string(65535)+# html :string(65535)+# js :string(65535)+# name :string not null+# share_key :string not null+# version_number :integer default(0), not null+# created_at :datetime not null+# updated_at :datetime not null+# ai_artifact_id :bigint not null+# user_id :integer not null+#+# Indexes+#+# index_ai_artifact_shares_on_ai_artifact_id (ai_artifact_id)+# index_ai_artifact_shares_on_share_key (share_key) UNIQUE+# index_ai_artifact_shares_on_user_id_and_ai_artifact_id (user_id,ai_artifact_id) UNIQUE+# index_ai_artifact_shares_on_user_id_and_created_at (user_id,created_at)+#diff --git a/plugins/discourse-ai/app/models/ai_artifact_share_key_value.rb b/plugins/discourse-ai/app/models/ai_artifact_share_key_value.rbnew file mode 100644index 00000000000..fb6f9e4a886--- /dev/null+++ b/plugins/discourse-ai/app/models/ai_artifact_share_key_value.rb@@ -0,0 +1,53 @@+# frozen_string_literal: true++class AiArtifactShareKeyValue < ActiveRecord::Base+ belongs_to :ai_artifact_share+ belongs_to :user++ validates :key, presence: true, length: { maximum: 50 }+ validates :value,+ presence: true,+ length: {+ maximum: ->(_) { SiteSetting.ai_artifact_kv_value_max_length },+ }+ attribute :public, :boolean, default: false+ validates :key, uniqueness: { scope: %i[ai_artifact_share_id user_id] }+ validate :validate_max_keys_per_user_per_share++ private++ def validate_max_keys_per_user_per_share+ return unless ai_artifact_share_id && user_id++ count = self.class.where(ai_artifact_share_id: ai_artifact_share_id, user_id: user_id).count+ count -= 1 if persisted?+ if count >= SiteSetting.ai_artifact_max_keys_per_user_per_artifact+ errors.add(+ :base,+ I18n.t(+ "discourse_ai.ai_artifact.errors.max_keys_exceeded",+ count: SiteSetting.ai_artifact_max_keys_per_user_per_artifact,+ ),+ )+ end+ end+end++# == Schema Information+#+# Table name: ai_artifact_share_key_values+#+# id :bigint not null, primary key+# key :string(50) not null+# public :boolean default(FALSE), not null+# value :string(20000) not null+# created_at :datetime not null+# updated_at :datetime not null+# ai_artifact_share_id :bigint not null+# user_id :integer not null+#+# Indexes+#+# index_ai_artifact_share_key_values_on_user_id (user_id)+# index_ai_artifact_share_kv_unique (ai_artifact_share_id,user_id,key) UNIQUE+#diff --git a/plugins/discourse-ai/app/models/shared_ai_conversation.rb b/plugins/discourse-ai/app/models/shared_ai_conversation.rbindex 781af3ef8b3..4a4bb6600ba 100644--- a/plugins/discourse-ai/app/models/shared_ai_conversation.rb+++ b/plugins/discourse-ai/app/models/shared_ai_conversation.rb@@ -98,9 +98,11 @@ class SharedAiConversation < ActiveRecord::Base"#{Discourse.base_uri}/discourse-ai/ai-bot/shared-ai-conversations/#{share_key}"end- def publicly_visible?- topic = target_topic- return false if topic.blank?+ def publicly_visible?(topic: nil, posts_by_id: nil)+ topic ||= target_topic+ if topic.blank? || target_type != "Topic" || topic.id != target_id || topic.deleted_at+ return false+ endsource_guardian = user.guardianreturn false if DiscourseAi::AiBot::EntryPoint.ai_share_error(topic, source_guardian)@@ -108,10 +110,11 @@ class SharedAiConversation < ActiveRecord::Basecontext_post_ids = context.filter_map { |context_post| context_post["id"] }return false if context_post_ids.blank?- posts_by_id = Post.where(id: context_post_ids, topic_id: topic.id).index_by(&:id)+ posts_by_id ||= Post.where(id: context_post_ids, topic_id: topic.id).index_by(&:id)context_post_ids.all? do |post_id|post = posts_by_id[post_id]- post.present? && source_guardian.can_see?(post)+ post.present? && post.id == post_id && post.topic_id == topic.id && !post.deleted_at &&+ source_guardian.can_see?(post)endenddiff --git a/plugins/discourse-ai/assets/javascripts/discourse/artifact-shares-route-map.js b/plugins/discourse-ai/assets/javascripts/discourse/artifact-shares-route-map.jsnew file mode 100644index 00000000000..7061e3a8f7e--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/artifact-shares-route-map.js@@ -0,0 +1,9 @@+export default {+ resource: "user.userActivity",++ map() {+ this.route("sharedAiArtifacts", { path: "shared-ai-artifacts" });+ this.route("sharedAiConversations", { path: "shared-ai-conversations" });+ this.route("sharedArtifacts", { path: "shared-artifacts" });+ },+};diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact-node-view.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact-node-view.gjsnew file mode 100644index 00000000000..b514eb9ce46--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact-node-view.gjs@@ -0,0 +1,159 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { next } from "@ember/runloop";+import { ajax } from "discourse/lib/ajax";+import DButton from "discourse/ui-kit/d-button";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import AiArtifactOptionsModal from "./modal/ai-artifact-options-modal";++function metadataPath({ share, id, version }) {+ if (share) {+ return `/discourse-ai/ai-bot/artifact-shares/${encodeURIComponent(share)}/metadata.json`;+ }++ return `/discourse-ai/ai-bot/artifacts/${encodeURIComponent(id)}/metadata.json${version ? `?version=${encodeURIComponent(version)}` : ""}`;+}++export default class AiArtifactNodeView extends Component {+ @tracked title;++ #destroyed = false;+ #identity;+ #request = 0;++ constructor() {+ super(...arguments);+ this.#identity = metadataPath(this.args.node.attrs);+ this.args.onSetup?.(this);+ this.#loadTitle(this.#identity);+ }++ willDestroy() {+ super.willDestroy(...arguments);+ this.#destroyed = true;+ this.#request++;+ }++ get displayTitle() {+ return this.title || i18n("discourse_ai.ai_artifact.editor.title");+ }++ get optionSummary() {+ const { autorun, height, seamless } = this.args.node.attrs;+ const defaultValue = i18n("discourse_ai.ai_artifact.editor.default");+ return [+ {+ name: "autorun",+ text: i18n("discourse_ai.ai_artifact.editor.summary_autorun", {+ value: this.#optionValue(autorun),+ }),+ },+ {+ name: "height",+ text: i18n("discourse_ai.ai_artifact.editor.summary_height", {+ value: height+ ? i18n("discourse_ai.ai_artifact.editor.summary_height_value", {+ height,+ })+ : defaultValue,+ }),+ },+ {+ name: "seamless",+ text: i18n("discourse_ai.ai_artifact.editor.summary_seamless", {+ value: this.#optionValue(seamless),+ }),+ },+ ];+ }++ @action+ openOptions() {+ const { node, view, getPos, pluginParams } = this.args;+ pluginParams.getContext().modal.show(AiArtifactOptionsModal, {+ model: {+ attrs: { ...node.attrs },+ siteSettings: pluginParams.getContext().siteSettings,+ onApply: (attrs) => {+ const pos = getPos();+ if (+ pos === undefined ||+ !view.state.doc.nodeAt(pos)?.sameMarkup(node)+ ) {+ return;+ }++ const tr = view.state.tr.setNodeMarkup(pos, null, attrs);+ tr.setSelection(+ pluginParams.pmState.NodeSelection.create(tr.doc, pos)+ );+ view.dispatch(tr);+ },+ restoreFocus: () => next(() => !view.isDestroyed && view.focus()),+ },+ });+ }++ update(node) {+ const identity = metadataPath(node.attrs);+ if (identity !== this.#identity) {+ this.#identity = identity;+ this.title = null;+ this.#loadTitle(identity);+ }+ }++ stopEvent(event) {+ return event.target instanceof Element && !!event.target.closest("button");+ }++ #loadTitle(identity) {+ const request = ++this.#request;+ ajax(identity)+ .then(({ name }) => {+ if (!this.#destroyed && request === this.#request) {+ this.title = typeof name === "string" ? name : null;+ }+ })+ .catch(() => {+ if (!this.#destroyed && request === this.#request) {+ this.title = null;+ }+ });+ }++ #optionValue(value) {+ return i18n(+ `discourse_ai.ai_artifact.editor.${+ value == null+ ? "default"+ : [true, "true", "1"].includes(value)+ ? "option_on"+ : "option_off"+ }`+ );+ }++ <template>+ <div class="composer-ai-artifact" contenteditable="false" ...attributes>+ <div class="composer-ai-artifact__content">+ <span class="composer-ai-artifact__title">{{dIcon+ "code"+ }}{{this.displayTitle}}</span>+ <div class="composer-ai-artifact__options">+ {{#each this.optionSummary as |option|}}+ <span data-option={{option.name}}>{{option.text}}</span>+ {{/each}}+ </div>+ </div>+ <DButton+ class="btn-flat composer-ai-artifact__edit"+ @action={{this.openOptions}}+ @icon="pencil"+ @label="discourse_ai.ai_artifact.editor.edit_options"+ />+ </div>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact-share.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact-share.gjsnew file mode 100644index 00000000000..8da92e16e13--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact-share.gjs@@ -0,0 +1,72 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import DButton from "discourse/ui-kit/d-button";+import AiArtifactShareModal from "./modal/ai-artifact-share-modal";++export default class AiArtifactShare extends Component {+ @service currentUser;+ @service modal;+ @service siteSettings;++ @tracked allowed = false;+ @tracked share = null;++ get canCheckEligibility() {+ return (+ this.currentUser?.can_share_ai_bot_conversations &&+ this.siteSettings.discourse_ai_enabled &&+ this.siteSettings.ai_bot_enabled &&+ this.siteSettings.ai_artifact_security !== "disabled"+ );+ }++ @action+ async load() {+ if (!this.canCheckEligibility) {+ return;+ }+ try {+ const result = await ajax(+ `/discourse-ai/ai-bot/artifact-shares/eligibility/${this.args.artifactId}.json`+ );+ this.allowed = result.can_share;+ this.share = result.share;+ } catch {+ // Passive check: a failure leaves sharing hidden instead of interrupting the reader.+ }+ }++ @action+ showShare() {+ this.modal.show(AiArtifactShareModal, {+ model: {+ artifactId: this.args.artifactId,+ artifactVersion: this.args.artifactVersion,+ onShareChange: this.updateShare,+ share: this.share,+ },+ });+ }++ @action+ updateShare(share) {+ this.share = share;+ }++ <template>+ <div class="ai-artifact-share" {{didInsert this.load}}>+ {{#if this.allowed}}+ <DButton+ class="btn-transparent ai-artifact-share__toggle"+ @action={{this.showShare}}+ @icon="share"+ @label="discourse_ai.ai_artifact.share"+ />+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjsindex 040e8de128b..f6e1644c0e3 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs@@ -7,6 +7,7 @@ import { trustHTML } from "@ember/template";import htmlClass from "discourse/helpers/html-class";import getURL from "discourse/lib/get-url";import DButton from "discourse/ui-kit/d-button";+import AiArtifactShare from "./ai-artifact-share";export default class AiArtifactComponent extends Component {@service siteSettings;@@ -48,11 +49,44 @@ export default class AiArtifactComponent extends Component {return this.siteSettings.ai_artifact_security !== "lax";}+ get hasShareKey() {+ return this.args.shareKey !== null && this.args.shareKey !== undefined;+ }++ get artifactIdentity() {+ if (this.hasShareKey) {+ return `share:${this.args.shareKey}`;+ }++ const version = String(this.args.artifactVersion ?? "").replace(/^0+/, "");+ return `artifact:${this.args.artifactId}:${version}`;+ }+get artifactUrl() {+ if (this.hasShareKey) {+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(this.args.shareKey)) {+ return;+ }++ return getURL(+ `/discourse-ai/ai-bot/artifact-shares/${encodeURIComponent(this.args.shareKey)}/forum`+ );+ }++ if (!/^[0-9]+$/.test(this.args.artifactId)) {+ return;+ }+let url = getURL(`/discourse-ai/ai-bot/artifacts/${this.args.artifactId}`);- if (this.args.artifactVersion) {- url = `${url}/${this.args.artifactVersion}`;+ const version = String(this.args.artifactVersion ?? "");+ if (version && !/^[0-9]+$/.test(version)) {+ return;+ }++ const normalizedVersion = version.replace(/^0+/, "");+ if (normalizedVersion) {+ url = `${url}/${encodeURIComponent(normalizedVersion)}`;}return url;}@@ -100,7 +134,11 @@ export default class AiArtifactComponent extends Component {@actionhandlePopState(event) {const state = event.state;- this.expanded = state?.artifactId === this.args.artifactId;+ this.expanded = state?.artifactIdentity+ ? state.artifactIdentity === this.artifactIdentity+ : !this.hasShareKey &&+ this.args.artifactId != null &&+ state?.artifactId === this.args.artifactId;if (!this.expanded) {window.removeEventListener("keydown", this.keydownHandler);}@@ -115,7 +153,10 @@ export default class AiArtifactComponent extends Component {toggleView() {if (!this.expanded) {window.history.pushState(- { artifactId: this.args.artifactId },+ {+ artifactId: this.args.artifactId,+ artifactIdentity: this.artifactIdentity,+ },"",window.location.href + "#artifact-fullscreen");@@ -159,7 +200,7 @@ export default class AiArtifactComponent extends Component {@label="discourse_ai.ai_artifact.click_to_run_label"/></div>- {{else}}+ {{else if this.artifactUrl}}<iframeframeborder="0"src={{this.artifactUrl}}@@ -170,6 +211,12 @@ export default class AiArtifactComponent extends Component {{{/if}}{{#if this.showFooter}}<div class="ai-artifact__footer">+ {{#unless this.hasShareKey}}+ <AiArtifactShare+ @artifactId={{@artifactId}}+ @artifactVersion={{@artifactVersion}}+ />+ {{/unless}}<DButtonclass="btn-transparent btn-icon-text ai-artifact__expand-button"@action={{this.toggleView}}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-sharing-activity-tabs.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-sharing-activity-tabs.gjsnew file mode 100644index 00000000000..9d6d28a176c--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-sharing-activity-tabs.gjs@@ -0,0 +1,42 @@+import Component from "@glimmer/component";+import { service } from "@ember/service";+import DNavigationItem from "discourse/ui-kit/d-navigation-item";+import { i18n } from "discourse-i18n";++export default class AiSharingActivityTabs extends Component {+ @service currentUser;+ @service siteSettings;++ get showConversations() {+ return (+ this.siteSettings.discourse_ai_enabled &&+ this.currentUser &&+ this.currentUser.id === this.args.outletArgs?.model?.id+ );+ }++ get showArtifacts() {+ return this.showConversations;+ }++ <template>+ {{#if this.showArtifacts}}+ <DNavigationItem+ class="user-nav__activity-shared-artifacts"+ @ariaCurrentContext="subNav"+ @route="userActivity.sharedAiArtifacts"+ >+ {{i18n "discourse_ai.ai_artifact.shared_artifacts"}}+ </DNavigationItem>+ {{/if}}+ {{#if this.showConversations}}+ <DNavigationItem+ class="user-nav__activity-shared-conversations"+ @ariaCurrentContext="subNav"+ @route="userActivity.sharedAiConversations"+ >+ {{i18n "discourse_ai.shared_ai_conversations.title"}}+ </DNavigationItem>+ {{/if}}+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-artifact-options-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-artifact-options-modal.gjsnew file mode 100644index 00000000000..8a6bd9a69b4--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-artifact-options-modal.gjs@@ -0,0 +1,247 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import Form from "discourse/components/form";+import getURL from "discourse/lib/get-url";+import DButton from "discourse/ui-kit/d-button";+import DModal from "discourse/ui-kit/d-modal";+import { i18n } from "discourse-i18n";++const SHARE_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;+const DECIMAL_PATTERN = /^[0-9]{1,19}$/;+const HEIGHT_PATTERN = /^[1-9][0-9]{0,3}$/;++function shareKey(reference) {+ if (SHARE_PATTERN.test(reference)) {+ return reference;+ }++ try {+ const url = new URL(reference, window.location.href);+ const prefix = getURL("/discourse-ai/ai-bot/artifact-shares/");+ if (+ url.origin === window.location.origin &&+ !url.search &&+ !url.hash &&+ url.pathname.startsWith(prefix)+ ) {+ const key = url.pathname.slice(prefix.length);+ if (SHARE_PATTERN.test(key)) {+ return key;+ }+ }+ } catch {+ return;+ }+}++function positiveDecimal(value) {+ return DECIMAL_PATTERN.test(value) && value.replace(/^0+/, "") !== "";+}++function normalizedDecimal(value) {+ return value.replace(/^0+/, "");+}++export default class AiArtifactOptionsModal extends Component {+ get isShare() {+ return this.args.model.attrs.share != null;+ }++ get formData() {+ const { share, id, version, autorun, height, seamless } =+ this.args.model.attrs;+ return {+ reference: share ?? id,+ version: version ?? "",+ autorun: autorun ?? "default",+ height: height ?? "",+ seamless:+ seamless == null+ ? "default"+ : ["true", "1"].includes(seamless)+ ? "true"+ : "false",+ };+ }++ get policyDescription() {+ const security = this.args.model.siteSettings.ai_artifact_security;+ if (security === "strict" || security === "lax") {+ return i18n(`discourse_ai.ai_artifact.editor.autorun_${security}`);+ }+ return i18n("discourse_ai.ai_artifact.editor.autorun_default_description");+ }++ @action+ validate(data, { addError, removeError }) {+ for (const name of ["reference", "version", "height"]) {+ removeError(name);+ }++ const invalid = (name, message) =>+ addError(name, {+ title: i18n(`discourse_ai.ai_artifact.editor.${name}`),+ message: i18n(`discourse_ai.ai_artifact.editor.${message}`),+ });++ if (+ this.isShare+ ? !shareKey(data.reference)+ : !positiveDecimal(data.reference)+ ) {+ invalid("reference", this.isShare ? "invalid_share" : "invalid_source");+ }+ if (!this.isShare && data.version && !positiveDecimal(data.version)) {+ invalid("version", "invalid_version");+ }+ if (+ data.height &&+ data.height !== this.formData.height &&+ (!HEIGHT_PATTERN.test(data.height) || Number(data.height) > 2000)+ ) {+ invalid("height", "invalid_height");+ }+ }++ @action+ apply(data) {+ const original = this.args.model.attrs;+ const attrs = {+ ...original,+ share: this.isShare ? shareKey(data.reference) : null,+ id: this.isShare ? null : normalizedDecimal(data.reference),+ version: this.isShare+ ? null+ : data.version+ ? normalizedDecimal(data.version)+ : null,+ autorun: data.autorun === "default" ? null : data.autorun,+ height: data.height || null,+ seamless:+ data.seamless === this.formData.seamless+ ? original.seamless+ : data.seamless === "default"+ ? null+ : data.seamless,+ };++ if (Object.keys(attrs).some((key) => attrs[key] !== original[key])) {+ this.args.model.onApply(attrs);+ }+ this.close();+ }++ @action+ close() {+ this.args.closeModal();+ this.args.model.restoreFocus();+ }++ <template>+ <DModal+ class="ai-artifact-options-modal"+ @closeModal={{this.close}}+ @title={{i18n "discourse_ai.ai_artifact.editor.edit_options"}}+ >+ <Form+ @data={{this.formData}}+ @onSubmit={{this.apply}}+ @validate={{this.validate}}+ as |form|+ >+ <form.Field+ @description={{i18n+ (if+ this.isShare+ "discourse_ai.ai_artifact.editor.share_reference_description"+ "discourse_ai.ai_artifact.editor.source_reference_description"+ )+ }}+ @format="full"+ @name="reference"+ @title={{i18n "discourse_ai.ai_artifact.editor.reference"}}+ @type="input"+ @validation="required"+ as |field|+ ><field.Control autofocus="autofocus" /></form.Field>++ {{#unless this.isShare}}+ <form.Field+ @description={{i18n+ "discourse_ai.ai_artifact.editor.version_description"+ }}+ @name="version"+ @title={{i18n "discourse_ai.ai_artifact.editor.version"}}+ @type="input"+ as |field|+ ><field.Control inputmode="numeric" /></form.Field>+ {{/unless}}++ <form.Field+ class="ai-artifact-options-modal__policy"+ @description={{this.policyDescription}}+ @name="autorun"+ @title={{i18n "discourse_ai.ai_artifact.editor.autorun"}}+ @type="select"+ as |field|+ >+ <field.Control as |select|>+ <select.Option @value="default">{{i18n+ "discourse_ai.ai_artifact.editor.default"+ }}</select.Option>+ <select.Option @value="true">{{i18n+ "discourse_ai.ai_artifact.editor.option_on"+ }}</select.Option>+ <select.Option @value="false">{{i18n+ "discourse_ai.ai_artifact.editor.option_off"+ }}</select.Option>+ </field.Control>+ </form.Field>++ <form.Field+ @description={{i18n+ "discourse_ai.ai_artifact.editor.height_description"+ }}+ @name="height"+ @title={{i18n "discourse_ai.ai_artifact.editor.height"}}+ @type="input"+ as |field|+ ><field.Control inputmode="numeric" /></form.Field>++ <form.Field+ @description={{i18n+ "discourse_ai.ai_artifact.editor.seamless_description"+ }}+ @name="seamless"+ @title={{i18n "discourse_ai.ai_artifact.editor.seamless"}}+ @type="select"+ as |field|+ >+ <field.Control as |select|>+ <select.Option @value="default">{{i18n+ "discourse_ai.ai_artifact.editor.default"+ }}</select.Option>+ <select.Option @value="true">{{i18n+ "discourse_ai.ai_artifact.editor.option_on"+ }}</select.Option>+ <select.Option @value="false">{{i18n+ "discourse_ai.ai_artifact.editor.option_off"+ }}</select.Option>+ </field.Control>+ </form.Field>++ <form.Actions>+ <DButton+ class="btn-transparent ai-artifact-options-modal__cancel"+ @action={{this.close}}+ @label="cancel"+ />+ <form.Submit+ class="ai-artifact-options-modal__apply"+ @label="discourse_ai.ai_artifact.editor.apply"+ />+ </form.Actions>+ </Form>+ </DModal>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-artifact-share-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-artifact-share-modal.gjsnew file mode 100644index 00000000000..f6510cc6a90--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-artifact-share-modal.gjs@@ -0,0 +1,253 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { clipboardCopy } from "discourse/lib/utilities";+import DButton from "discourse/ui-kit/d-button";+import DModal from "discourse/ui-kit/d-modal";+import { i18n } from "discourse-i18n";+import { formatAiArtifactPostEmbed } from "discourse/plugins/discourse-ai/discourse/lib/ai-artifact-embed";++export default class AiArtifactShareModal extends Component {+ @service dialog;+ @service siteSettings;+ @service toasts;++ @tracked busy = false;+ @tracked confirmationOpen = false;+ @tracked share = null;++ constructor() {+ super(...arguments);+ this.share = this.args.model.share;+ }++ get blocked() {+ return this.busy || this.confirmationOpen;+ }++ get viewedVersion() {+ return this.args.model.artifactVersion == null+ ? 0+ : Number(this.args.model.artifactVersion);+ }++ get endpoint() {+ return `/discourse-ai/ai-bot/artifact-shares/${this.args.model.artifactId}`;+ }++ @action+ async create() {+ if (this.blocked) {+ return;+ }+ this.busy = true;+ try {+ this.share = await ajax(`${this.endpoint}.json`, {+ type: "POST",+ data: { version: this.viewedVersion },+ });+ this.args.model.onShareChange(this.share);+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.busy = false;+ }+ }++ @action+ async update() {+ if (this.blocked) {+ return;+ }+ this.busy = true;+ try {+ this.share = await ajax(+ `/discourse-ai/ai-bot/artifact-shares/${this.share.share_key}.json`,+ {+ type: "PUT",+ data: { version: this.viewedVersion },+ }+ );+ this.args.model.onShareChange(this.share);+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_artifact.pin_updated") },+ });+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.busy = false;+ }+ }++ @action+ revoke() {+ if (this.blocked || !this.share) {+ return;+ }+ this.confirmationOpen = true;+ return this.dialog.confirm({+ title: i18n("discourse_ai.ai_artifact.confirm_revoke_standalone_title"),+ message: i18n(+ "discourse_ai.ai_artifact.confirm_revoke_standalone_message"+ ),+ confirmButtonLabel: "discourse_ai.ai_artifact.revoke",+ confirmButtonClass: "btn-danger",+ didConfirm: () => this.#revokeConfirmed(),+ didCancel: () => {+ this.confirmationOpen = false;+ },+ });+ }++ @action+ async copyLink() {+ if (this.blocked || !this.share) {+ return;+ }+ try {+ await clipboardCopy(this.share.url);+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_artifact.copied") },+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ async copyPostEmbed() {+ if (this.blocked || !this.share) {+ return;+ }+ try {+ await clipboardCopy(formatAiArtifactPostEmbed(this.share));+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_artifact.copied") },+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ async copyWebsiteEmbed() {+ if (this.blocked || !this.share) {+ return;+ }+ try {+ await clipboardCopy(+ `<iframe src="${this.share.url}" width="100%" height="600" frameborder="0"></iframe>`+ );+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_artifact.copied") },+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ async #revokeConfirmed() {+ this.busy = true;+ try {+ await ajax(+ `/discourse-ai/ai-bot/artifact-shares/${this.share.share_key}.json`,+ { type: "DELETE" }+ );+ this.share = null;+ this.args.model.onShareChange(null);+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.busy = false;+ this.confirmationOpen = false;+ }+ }++ <template>+ <DModal+ class="ai-artifact-share-modal"+ @closeModal={{@closeModal}}+ @title={{i18n "discourse_ai.ai_artifact.share"}}+ >+ <:body>+ <p>{{i18n+ (if+ this.siteSettings.login_required+ "discourse_ai.ai_artifact.privacy_notice_login_required"+ "discourse_ai.ai_artifact.privacy_notice"+ )+ }}</p>+ {{#if this.share}}+ <p>+ <a+ class="ai-artifact-share-modal__link"+ href={{this.share.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{this.share.url}}</a>+ </p>+ <div class="ai-artifact-share-modal__actions">+ <DButton+ class="ai-artifact-share-modal__copy-link"+ @action={{this.copyLink}}+ @disabled={{this.blocked}}+ @icon="link"+ @label="discourse_ai.ai_artifact.copy_link"+ />+ <DButton+ class="ai-artifact-share-modal__embed-post"+ @action={{this.copyPostEmbed}}+ @disabled={{this.blocked}}+ @icon="code"+ @label="discourse_ai.ai_artifact.embed_post"+ @title="discourse_ai.ai_artifact.embed_post_title"+ />+ <DButton+ class="ai-artifact-share-modal__embed-website"+ @action={{this.copyWebsiteEmbed}}+ @disabled={{this.blocked}}+ @icon="code"+ @label="discourse_ai.ai_artifact.embed_website"+ @title="discourse_ai.ai_artifact.embed_website_title"+ />+ <DButton+ rel="noopener noreferrer"+ target="_blank"+ @href={{this.share.url}}+ @label="discourse_ai.ai_artifact.new_tab"+ />+ <DButton+ class="ai-artifact-share-modal__update"+ @action={{this.update}}+ @disabled={{this.blocked}}+ @icon="arrows-rotate"+ @label="discourse_ai.ai_artifact.update_pin"+ />+ <DButton+ class="btn-danger ai-artifact-share-modal__revoke"+ @action={{this.revoke}}+ @disabled={{this.blocked}}+ @icon="far-trash-can"+ @label="discourse_ai.ai_artifact.revoke"+ />+ </div>+ {{else}}+ <DButton+ class="btn-primary ai-artifact-share-modal__create"+ @action={{this.create}}+ @disabled={{this.busy}}+ @isLoading={{this.busy}}+ @label="discourse_ai.ai_artifact.create_link"+ />+ {{/if}}+ </:body>+ </DModal>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/share-full-topic-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/share-full-topic-modal.gjsindex 8378d270448..6dec52d6f85 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/share-full-topic-modal.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/share-full-topic-modal.gjs@@ -1,33 +1,44 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";-import { on } from "@ember/modifier";import { action } from "@ember/object";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { getAbsoluteURL } from "discourse/lib/get-url";-import { clipboardCopyAsync } from "discourse/lib/utilities";+import { clipboardCopyAsync, escapeExpression } from "discourse/lib/utilities";import DButton from "discourse/ui-kit/d-button";import DModal from "discourse/ui-kit/d-modal";import { i18n } from "discourse-i18n";export default class ShareModal extends Component {+ @service dialog;@service toasts;+ @tracked confirmationOpen = false;+ @tracked deleting = false;@tracked shareKey = "";+ @tracked sharing = false;constructor() {super(...arguments);this.shareKey = this.args.model.share_key;}+ get busy() {+ return this.sharing || this.deleting || this.confirmationOpen;+ }+get htmlContext() {let context = [];this.args.model.context.forEach((post) => {- context.push(`<p><b>${post.username}:</b></p>`);- context.push(post.cooked);+ const preview = new DOMParser().parseFromString(post.cooked, "text/html");+ preview+ .querySelectorAll(".ai-artifact-controls, .copy-embed")+ .forEach((control) => control.remove());+ context.push(`<p><b>${escapeExpression(post.username)}:</b></p>`);+ context.push(preview.body.innerHTML);});return trustHTML(context.join("\n"));}@@ -39,81 +50,74 @@ export default class ShareModal extends Component {}async generateShareURL() {- try {- const response = await ajax(- "/discourse-ai/ai-bot/shared-ai-conversations",- {- type: "POST",- data: {- topic_id: this.args.model.topic_id,- },- }- );-- const url = getAbsoluteURL(- `/discourse-ai/ai-bot/shared-ai-conversations/${response.share_key}`- );- this.shareKey = response.share_key;-- return new Blob([url], { type: "text/plain" });- } catch (e) {- popupAjaxError(e);- return;- }+ const response = await ajax(+ "/discourse-ai/ai-bot/shared-ai-conversations",+ {+ type: "POST",+ data: { topic_id: this.args.model.topic_id },+ }+ );+ const url = getAbsoluteURL(+ `/discourse-ai/ai-bot/shared-ai-conversations/${response.share_key}`+ );+ this.shareKey = response.share_key;++ return new Blob([url], { type: "text/plain" });}@action- async deleteLink() {- try {- await ajax(- `/discourse-ai/ai-bot/shared-ai-conversations/${this.shareKey}.json`,- {- type: "DELETE",- }- );-- this.shareKey = null;- } catch (e) {- popupAjaxError(e);+ deleteLink() {+ if (this.busy || !this.shareKey) {+ return;}- }-- @action- async share() {- await clipboardCopyAsync(this.generateShareURL.bind(this));- this.toasts.success({- duration: "short",- data: {- message: i18n("discourse_ai.ai_bot.conversation_shared"),+ this.confirmationOpen = true;+ return this.dialog.confirm({+ title: i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_title"),+ message: i18n(+ "discourse_ai.ai_artifact.confirm_revoke_conversation_message"+ ),+ confirmButtonLabel: "discourse_ai.ai_artifact.revoke_conversation",+ confirmButtonClass: "btn-danger",+ didConfirm: () => this.#deleteConfirmed(),+ didCancel: () => {+ this.confirmationOpen = false;},});}@action- async maybeCopyEmbed(event) {- if (!event.target.classList.contains("copy-embed")) {- return true;+ async share() {+ if (this.busy) {+ return;}- event.stopPropagation();- event.preventDefault();-- let version = "";- if (event.target.dataset.artifactVersion) {- version = `data-ai-artifact-version="${event.target.dataset.artifactVersion}"`;+ this.sharing = true;+ try {+ await clipboardCopyAsync(this.generateShareURL.bind(this));+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_bot.conversation_shared") },+ });+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.sharing = false;}- const artifactEmbed = `<div class="ai-artifact" ${version} data-ai-artifact-id="${event.target.dataset.artifactId}"></div>`;- const promise = new Promise((resolve) => {- resolve(artifactEmbed);- });-- await clipboardCopyAsync(() => promise);+ }- this.toasts.success({- duration: "short",- data: {- message: i18n("discourse_ai.ai_bot.embed_copied"),- },- });+ async #deleteConfirmed() {+ this.deleting = true;+ try {+ await ajax(+ `/discourse-ai/ai-bot/shared-ai-conversations/${this.shareKey}.json`,+ { type: "DELETE" }+ );+ this.shareKey = null;+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.deleting = false;+ this.confirmationOpen = false;+ }}<template>@@ -123,20 +127,16 @@ export default class ShareModal extends Component {@title={{i18n "discourse_ai.ai_bot.share_full_topic_modal.title"}}><:body>- {{! eslint-disable ember/template-no-invalid-interactive }}- <div- class="ai-share-full-topic-modal__body"- {{on "click" this.maybeCopyEmbed}}- >+ <div class="ai-share-full-topic-modal__body">{{this.htmlContext}}</div>- {{! eslint-enable }}</:body><:footer><DButtonclass="btn-primary confirm"@action={{this.share}}+ @disabled={{this.busy}}@icon="copy"@label={{this.primaryLabel}}/>@@ -144,6 +144,7 @@ export default class ShareModal extends Component {<DButtonclass="btn-danger"@action={{this.deleteLink}}+ @disabled={{this.busy}}@icon="far-trash-can"@label="discourse_ai.ai_bot.share_full_topic_modal.delete"/>diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/shared-artifacts-list.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/shared-artifacts-list.gjsnew file mode 100644index 00000000000..50df429d743--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/shared-artifacts-list.gjs@@ -0,0 +1,379 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { shortDate } from "discourse/lib/formatter";+import { getAbsoluteURL } from "discourse/lib/get-url";+import { clipboardCopy } from "discourse/lib/utilities";+import { eq, or } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DLoadMore from "discourse/ui-kit/d-load-more";+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";+import { i18n } from "discourse-i18n";+import { formatAiArtifactPostEmbed } from "discourse/plugins/discourse-ai/discourse/lib/ai-artifact-embed";++const SHARES_URL = "/discourse-ai/ai-bot/artifact-shares.json";++export default class SharedArtifactsList extends Component {+ @service dialog;+ @service toasts;++ @tracked items;+ @tracked hasMore;+ @tracked nextCursor;+ @tracked filter = "all";+ @tracked order = "newest";+ @tracked loading = false;+ @tracked loadError = false;+ @tracked _revokeConfirmationOpen = false;++ constructor() {+ super(...arguments);+ this.items = this.args.data.items;+ this.hasMore = this.args.data.has_more;+ this.nextCursor = this.args.data.next_cursor;+ }++ get canLoadMore() {+ return this.hasMore && !this.loadError && !this._revokeConfirmationOpen;+ }++ formattedDate(date) {+ return shortDate(new Date(date));+ }++ @action+ async copyLink(item) {+ if (this.loading || this._revokeConfirmationOpen || !item.available) {+ return;+ }+ await this.#copy(this.#absoluteURL(item.url));+ }++ @action+ async copyPostEmbed(item) {+ if (this.loading || this._revokeConfirmationOpen || !item.available) {+ return;+ }+ await this.#copy(formatAiArtifactPostEmbed(item));+ }++ @action+ async copyWebsiteEmbed(item) {+ if (this.loading || this._revokeConfirmationOpen || !item.available) {+ return;+ }+ const url = this.#absoluteURL(item.embed_url || item.url);+ await this.#copy(+ `<iframe src="${url}" width="100%" height="600" frameborder="0"></iframe>`+ );+ }++ @action+ revoke(item) {+ if (this.loading || this._revokeConfirmationOpen) {+ return;+ }++ this._revokeConfirmationOpen = true;+ const isConversation = item.type === "conversation";+ return this.dialog.confirm({+ title: i18n(+ `discourse_ai.ai_artifact.confirm_revoke_${isConversation ? "conversation" : "standalone"}_title`+ ),+ message: i18n(+ `discourse_ai.ai_artifact.confirm_revoke_${isConversation ? "conversation" : "standalone"}_message`+ ),+ confirmButtonLabel: isConversation+ ? "discourse_ai.ai_artifact.revoke_conversation"+ : "discourse_ai.ai_artifact.revoke",+ confirmButtonClass: "btn-danger",+ didConfirm: () => {+ this._revokeConfirmationOpen = false;+ this.#revokeConfirmed(item);+ },+ didCancel: () => {+ this._revokeConfirmationOpen = false;+ },+ });+ }++ @action+ async changeFilter(filter) {+ if (+ this.loading ||+ this._revokeConfirmationOpen ||+ filter === this.filter+ ) {+ return;+ }+ await this.#reload(filter, this.order);+ }++ @action+ async toggleSort() {+ if (this.loading || this._revokeConfirmationOpen) {+ return;+ }+ await this.#reload(+ this.filter,+ this.order === "newest" ? "oldest" : "newest"+ );+ }++ @action+ async loadMore() {+ if (this.loading || this._revokeConfirmationOpen || !this.canLoadMore) {+ return;+ }+ this.loading = true;+ try {+ const result = await this.#fetch(+ this.filter,+ this.order,+ this.nextCursor+ );+ this.items = [...this.items, ...result.items];+ this.hasMore = result.has_more;+ this.nextCursor = result.next_cursor;+ this.loadError = false;+ } catch {+ this.loadError = true;+ } finally {+ this.loading = false;+ }+ }++ @action+ retryLoad() {+ if (this.loading || this._revokeConfirmationOpen || !this.loadError) {+ return;+ }+ this.loadError = false;+ return this.loadMore();+ }++ async #revokeConfirmed(item) {+ if (this.loading) {+ return;+ }+ this.loading = true;+ try {+ const collection =+ item.type === "conversation"+ ? "shared-ai-conversations"+ : "artifact-shares";+ await ajax(`/discourse-ai/ai-bot/${collection}/${item.share_key}.json`, {+ type: "DELETE",+ });+ this.items = this.items.filter((entry) =>+ item.type === "conversation"+ ? entry.type !== "conversation" || entry.share_key !== item.share_key+ : entry.id !== item.id+ );+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.loading = false;+ }+ }++ async #reload(filter, order) {+ this.loading = true;+ try {+ const result = await this.#fetch(filter, order);+ this.filter = filter;+ this.order = order;+ this.items = result.items;+ this.hasMore = result.has_more;+ this.nextCursor = result.next_cursor;+ this.loadError = false;+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.loading = false;+ }+ }++ #fetch(filter, order, cursor) {+ return ajax(SHARES_URL, {+ data: {+ type: filter,+ order,+ ...(cursor !== null && cursor !== undefined+ ? { cursor: JSON.stringify(cursor) }+ : {}),+ },+ });+ }++ #absoluteURL(url) {+ if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(url)) {+ return url;+ }+ return getAbsoluteURL(url.startsWith("/") ? url : `/${url}`);+ }++ #copy(text) {+ return clipboardCopy(text)+ .then(() =>+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_artifact.copied") },+ })+ )+ .catch((error) => popupAjaxError(error));+ }++ <template>+ <section+ aria-labelledby="shared-artifacts-heading"+ class="shared-artifacts"+ ...attributes+ >+ <h2 id="shared-artifacts-heading">{{i18n+ "discourse_ai.ai_artifact.shared_artifacts"+ }}</h2>+ <div class="shared-artifacts__controls">+ <div+ aria-label={{i18n "discourse_ai.ai_artifact.filter_shares"}}+ class="shared-artifacts__filters"+ role="group"+ >+ <DButton+ class="btn-flat"+ @action={{fn this.changeFilter "all"}}+ @ariaPressed={{eq this.filter "all"}}+ @disabled={{this.loading}}+ @label="discourse_ai.ai_artifact.filter_all"+ />+ <DButton+ class="btn-flat"+ @action={{fn this.changeFilter "standalone"}}+ @ariaPressed={{eq this.filter "standalone"}}+ @disabled={{this.loading}}+ @label="discourse_ai.ai_artifact.filter_standalone"+ />+ <DButton+ class="btn-flat"+ @action={{fn this.changeFilter "conversation"}}+ @ariaPressed={{eq this.filter "conversation"}}+ @disabled={{this.loading}}+ @label="discourse_ai.ai_artifact.filter_conversation"+ />+ </div>+ <DButton+ class="btn-flat shared-artifacts__sort"+ @action={{this.toggleSort}}+ @disabled={{this.loading}}+ @icon="chevron-down"+ @label={{if+ (eq this.order "oldest")+ "discourse_ai.ai_artifact.oldest_first"+ "discourse_ai.ai_artifact.newest_first"+ }}+ />+ </div>+ <DLoadMore+ @action={{this.loadMore}}+ @enabled={{this.canLoadMore}}+ @isLoading={{or this.loading this.loadError}}+ >+ <ol class="shared-artifacts__list">+ {{#each this.items key="id" as |item|}}+ <li class="shared-artifacts__card">+ <div class="shared-artifacts__details">+ <h3>+ {{#if item.available}}+ <a+ href={{item.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{item.name}}</a>+ {{else}}+ {{item.name}}+ {{/if}}+ </h3>+ <div class="shared-artifacts__meta">+ <small>{{i18n+ (if+ (eq item.type "standalone")+ "discourse_ai.ai_artifact.standalone"+ "discourse_ai.ai_artifact.conversation"+ )+ }}</small>+ {{#if item.created_at}}+ <small>{{this.formattedDate item.created_at}}</small>+ {{/if}}+ </div>+ {{#unless item.available}}+ <p class="shared-artifacts__unavailable">{{i18n+ "discourse_ai.ai_artifact.unavailable"+ }}</p>+ {{/unless}}+ </div>+ <div class="shared-artifacts__actions">+ {{#if item.available}}+ <DButton+ class="btn-default shared-artifacts__copy-link"+ @action={{fn this.copyLink item}}+ @disabled={{this.loading}}+ @icon="link"+ @label="discourse_ai.ai_artifact.copy_link"+ />+ <DButton+ class="btn-default shared-artifacts__embed-post"+ @action={{fn this.copyPostEmbed item}}+ @disabled={{this.loading}}+ @icon="code"+ @label="discourse_ai.ai_artifact.embed_post"+ @title="discourse_ai.ai_artifact.embed_post_title"+ />+ <DButton+ class="btn-default shared-artifacts__embed-website"+ @action={{fn this.copyWebsiteEmbed item}}+ @disabled={{this.loading}}+ @icon="code"+ @label="discourse_ai.ai_artifact.embed_website"+ @title="discourse_ai.ai_artifact.embed_website_title"+ />+ {{/if}}+ <DButton+ class="btn-danger shared-artifacts__revoke"+ @action={{fn this.revoke item}}+ @disabled={{this.loading}}+ @icon="far-trash-can"+ @label={{if+ (eq item.type "conversation")+ "discourse_ai.ai_artifact.revoke_conversation"+ "discourse_ai.ai_artifact.revoke"+ }}+ />+ </div>+ </li>+ {{else}}+ {{#unless this.hasMore}}+ <li class="shared-artifacts__empty">{{i18n+ "discourse_ai.ai_artifact.empty_shares"+ }}</li>+ {{/unless}}+ {{/each}}+ </ol>+ </DLoadMore>+ {{#if this.loading}}+ <div class="shared-artifacts__loading">{{dLoadingSpinner}}</div>+ {{/if}}+ {{#if this.loadError}}+ <DButton+ class="shared-artifacts__retry"+ @action={{this.retryLoad}}+ @disabled={{this.loading}}+ @label="discourse_ai.ai_artifact.retry_loading"+ />+ {{/if}}+ </section>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/shared-conversations-list.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/shared-conversations-list.gjsnew file mode 100644index 00000000000..b13d1f44ccc--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/shared-conversations-list.gjs@@ -0,0 +1,261 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { shortDate } from "discourse/lib/formatter";+import { getAbsoluteURL } from "discourse/lib/get-url";+import { clipboardCopy } from "discourse/lib/utilities";+import { eq, or } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DLoadMore from "discourse/ui-kit/d-load-more";+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";+import { i18n } from "discourse-i18n";++const SHARES_URL = "/discourse-ai/ai-bot/shared-ai-conversations.json";++export default class SharedConversationsList extends Component {+ @service dialog;+ @service toasts;++ @tracked items;+ @tracked hasMore;+ @tracked nextCursor;+ @tracked order = "newest";+ @tracked loading = false;+ @tracked loadError = false;+ @tracked _revokeConfirmationOpen = false;++ constructor() {+ super(...arguments);+ this.items = this.args.data.items;+ this.hasMore = this.args.data.has_more;+ this.nextCursor = this.args.data.next_cursor;+ }++ get canLoadMore() {+ return this.hasMore && !this.loadError && !this._revokeConfirmationOpen;+ }++ formattedDate(date) {+ return shortDate(new Date(date));+ }++ @action+ async copyLink(item) {+ if (this.loading || this._revokeConfirmationOpen || !item.available) {+ return;+ }+ const url = /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(item.url)+ ? item.url+ : getAbsoluteURL(item.url.startsWith("/") ? item.url : `/${item.url}`);+ try {+ await clipboardCopy(url);+ this.toasts.success({+ duration: "short",+ data: { message: i18n("discourse_ai.ai_artifact.copied") },+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ revoke(item) {+ if (this.loading || this._revokeConfirmationOpen) {+ return;+ }++ this._revokeConfirmationOpen = true;+ return this.dialog.confirm({+ title: i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_title"),+ message: i18n(+ "discourse_ai.ai_artifact.confirm_revoke_conversation_message"+ ),+ confirmButtonLabel: "discourse_ai.ai_artifact.revoke_conversation",+ confirmButtonClass: "btn-danger",+ didConfirm: () => {+ this._revokeConfirmationOpen = false;+ this.#revokeConfirmed(item);+ },+ didCancel: () => {+ this._revokeConfirmationOpen = false;+ },+ });+ }++ @action+ async toggleSort() {+ if (this.loading || this._revokeConfirmationOpen) {+ return;+ }+ this.loading = true;+ try {+ const order = this.order === "newest" ? "oldest" : "newest";+ const result = await this.#fetch(order);+ this.order = order;+ this.items = result.items;+ this.hasMore = result.has_more;+ this.nextCursor = result.next_cursor;+ this.loadError = false;+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.loading = false;+ }+ }++ @action+ async loadMore() {+ if (this.loading || this._revokeConfirmationOpen || !this.canLoadMore) {+ return;+ }+ this.loading = true;+ try {+ const result = await this.#fetch(this.order, this.nextCursor);+ this.items = [...this.items, ...result.items];+ this.hasMore = result.has_more;+ this.nextCursor = result.next_cursor;+ this.loadError = false;+ } catch {+ this.loadError = true;+ } finally {+ this.loading = false;+ }+ }++ @action+ retryLoad() {+ if (this.loading || this._revokeConfirmationOpen || !this.loadError) {+ return;+ }+ this.loadError = false;+ return this.loadMore();+ }++ async #revokeConfirmed(item) {+ if (this.loading) {+ return;+ }+ this.loading = true;+ try {+ await ajax(+ `/discourse-ai/ai-bot/shared-ai-conversations/${item.share_key}.json`,+ { type: "DELETE" }+ );+ this.items = this.items.filter((entry) => entry.id !== item.id);+ } catch (error) {+ popupAjaxError(error);+ } finally {+ this.loading = false;+ }+ }++ #fetch(order, cursor) {+ return ajax(SHARES_URL, {+ data: {+ order,+ ...(cursor !== null && cursor !== undefined+ ? { cursor: JSON.stringify(cursor) }+ : {}),+ },+ });+ }++ <template>+ <section+ aria-labelledby="shared-conversations-heading"+ class="shared-conversations"+ ...attributes+ >+ <h2 id="shared-conversations-heading">{{i18n+ "discourse_ai.shared_ai_conversations.title"+ }}</h2>+ <div class="shared-conversations__controls">+ <DButton+ class="btn-flat shared-conversations__sort"+ @action={{this.toggleSort}}+ @disabled={{this.loading}}+ @icon="chevron-down"+ @label={{if+ (eq this.order "oldest")+ "discourse_ai.ai_artifact.oldest_first"+ "discourse_ai.ai_artifact.newest_first"+ }}+ />+ </div>+ <DLoadMore+ @action={{this.loadMore}}+ @enabled={{this.canLoadMore}}+ @isLoading={{or this.loading this.loadError}}+ >+ <ol class="shared-conversations__list">+ {{#each this.items key="id" as |item|}}+ <li class="shared-conversations__card">+ <div class="shared-conversations__details">+ <h3>+ {{#if item.available}}+ <a+ href={{item.url}}+ rel="noopener noreferrer"+ target="_blank"+ >{{item.title}}</a>+ {{else}}+ {{item.title}}+ {{/if}}+ </h3>+ {{#if item.created_at}}+ <div class="shared-conversations__meta">+ <small>{{this.formattedDate item.created_at}}</small>+ </div>+ {{/if}}+ {{#unless item.available}}+ <p class="shared-conversations__unavailable">{{i18n+ "discourse_ai.shared_ai_conversations.unavailable"+ }}</p>+ {{/unless}}+ </div>+ <div class="shared-conversations__actions">+ {{#if item.available}}+ <DButton+ class="btn-default shared-conversations__copy-link"+ @action={{fn this.copyLink item}}+ @disabled={{this.loading}}+ @icon="link"+ @label="discourse_ai.ai_artifact.copy_link"+ />+ {{/if}}+ <DButton+ class="btn-danger shared-conversations__revoke"+ @action={{fn this.revoke item}}+ @disabled={{this.loading}}+ @icon="far-trash-can"+ @label="discourse_ai.ai_artifact.revoke_conversation"+ />+ </div>+ </li>+ {{else}}+ {{#unless this.hasMore}}+ <li class="shared-conversations__empty">{{i18n+ "discourse_ai.shared_ai_conversations.empty"+ }}</li>+ {{/unless}}+ {{/each}}+ </ol>+ </DLoadMore>+ {{#if this.loading}}+ <div class="shared-conversations__loading">{{dLoadingSpinner}}</div>+ {{/if}}+ {{#if this.loadError}}+ <DButton+ class="shared-conversations__retry"+ @action={{this.retryLoad}}+ @disabled={{this.loading}}+ @label="discourse_ai.ai_artifact.retry_loading"+ />+ {{/if}}+ </section>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-rich-editor.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-rich-editor.jsnew file mode 100644index 00000000000..b9a91c006f9--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-rich-editor.js@@ -0,0 +1,8 @@+import { apiInitializer } from "discourse/lib/api";+import richEditorExtension from "../lib/ai-artifact-rich-editor-extension";++export default apiInitializer((api) => {+ if (api.container.lookup("service:site-settings").discourse_ai_enabled) {+ api.registerRichEditorExtension(richEditorExtension);+ }+});diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-shares.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-shares.gjsnew file mode 100644index 00000000000..84275aa0293--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-shares.gjs@@ -0,0 +1,6 @@+import { apiInitializer } from "discourse/lib/api";+import AiSharingActivityTabs from "../components/ai-sharing-activity-tabs";++export default apiInitializer((api) => {+ api.renderInOutlet("user-activity-bottom", AiSharingActivityTabs);+});diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifacts.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifacts.gjsindex f82264b5959..9a6fc1e4dc5 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifacts.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifacts.gjs@@ -10,6 +10,10 @@ function initializeAiArtifacts(api) {[...element.querySelectorAll("div.ai-artifact")].forEach((artifactElement) => {+ const shareKey = artifactElement.getAttribute(+ "data-ai-artifact-share-key"+ );+const artifactId = artifactElement.getAttribute("data-ai-artifact-id");@@ -34,6 +38,7 @@ function initializeAiArtifacts(api) {for (const attr of artifactElement.attributes) {if (attr.name.startsWith("data-") &&+ attr.name !== "data-ai-artifact-share-key" &&attr.name !== "data-ai-artifact-id" &&attr.name !== "data-ai-artifact-version" &&attr.name !== "data-ai-artifact-height" &&@@ -54,6 +59,7 @@ function initializeAiArtifacts(api) {@autorun={{autorun}}@dataAttributes={{dataAttributes}}@seamless={{seamless}}+ @shareKey={{shareKey}}/></template>);diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-artifact-embed.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-artifact-embed.jsnew file mode 100644index 00000000000..52f06b02fbb--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-artifact-embed.js@@ -0,0 +1,11 @@+export function formatAiArtifactPostEmbed(item) {+ if (item.type === "conversation") {+ const version =+ Number(item.artifact_version) > 0+ ? ` version="${item.artifact_version}"`+ : "";+ return `[ai-artifact id="${item.artifact_id}"${version}]`;+ }++ return `[ai-artifact share="${item.share_key}"]`;+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-artifact-rich-editor-extension.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-artifact-rich-editor-extension.jsnew file mode 100644index 00000000000..d8bd4dfc6f7--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-artifact-rich-editor-extension.js@@ -0,0 +1,275 @@+import AiArtifactNodeView from "../components/ai-artifact-node-view";++const SHARE_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;+const DECIMAL_PATTERN = /^[0-9]{1,19}$/;+const HEIGHT_PATTERN = /^[0-9]{1,19}$/;++function normalizedHeight(value) {+ if (value == null || !HEIGHT_PATTERN.test(value)) {+ return null;+ }+ const height = Number(value);+ return height > 0 && height <= 2000 ? String(height) : null;+}++const TAG_PATTERN = /^\[ai-artifact((?:[ \t]+[a-z]+="[^"\r\n]*")+)\]$/;+const ATTRIBUTE_PATTERN = /[ \t]+([a-z]+)="([^"\r\n]*)"/g;++function normalizeIdentity({ share, id, version, autorun }) {+ if (+ autorun !== null &&+ autorun !== undefined &&+ !["true", "false"].includes(autorun)+ ) {+ return;+ }++ if (share !== null && share !== undefined) {+ if (id != null || version != null || !SHARE_PATTERN.test(share)) {+ return;+ }+ return { share, id: null, version: null, autorun: autorun ?? null };+ }++ if (+ !DECIMAL_PATTERN.test(id || "") ||+ (version != null && !DECIMAL_PATTERN.test(version))+ ) {+ return;+ }++ id = id.replace(/^0+/, "");+ if (!id) {+ return;+ }++ return {+ share: null,+ id,+ version: version?.replace(/^0+/, "") || null,+ autorun: autorun ?? null,+ };+}++function parseTag(tag) {+ const match = TAG_PATTERN.exec(tag);+ if (!match) {+ return;+ }++ const attrs = Object.create(null);+ for (const [, name, value] of match[1].matchAll(ATTRIBUTE_PATTERN)) {+ if (+ !["share", "id", "version", "autorun", "height", "seamless"].includes(+ name+ ) ||+ name in attrs+ ) {+ return;+ }+ attrs[name] = value;+ }++ const identity = normalizeIdentity(attrs);+ const height = attrs.height == null ? null : normalizedHeight(attrs.height);+ if (+ !identity ||+ (attrs.height != null && height === null) ||+ (attrs.seamless != null && !["true", "false"].includes(attrs.seamless))+ ) {+ return;+ }+ return { ...identity, height, seamless: attrs.seamless ?? null };+}++function attrsFromDOM(dom) {+ const autorun = dom.getAttribute("data-ai-artifact-autorun");+ const identity = normalizeIdentity({+ share: dom.getAttribute("data-ai-artifact-share-key"),+ id: dom.getAttribute("data-ai-artifact-id"),+ version: dom.getAttribute("data-ai-artifact-version"),+ autorun:+ autorun == null+ ? null+ : autorun === "" || autorun === "1" || autorun === "true"+ ? "true"+ : "false",+ });+ if (!identity) {+ return false;+ }++ return {+ ...identity,+ height: dom.getAttribute("data-ai-artifact-height"),+ width: dom.getAttribute("data-ai-artifact-width"),+ seamless: dom.getAttribute("data-ai-artifact-seamless"),+ };+}++function compactTag({ share, id, version, autorun, height, seamless }) {+ const identity = share ? `share="${share}"` : `id="${id}"`;+ return `[ai-artifact ${identity}${version ? ` version="${version}"` : ""}${autorun != null ? ` autorun="${autorun}"` : ""}${height != null ? ` height="${normalizedHeight(height)}"` : ""}${seamless != null ? ` seamless="${seamless}"` : ""}]`;+}++function escapeAttribute(value) {+ return String(value)+ .replaceAll("&", "&")+ .replaceAll('"', """)+ .replaceAll("<", "<")+ .replaceAll(">", ">");+}++function artifactHTML(attrs) {+ const dataAttrs = {+ "data-ai-artifact-share-key": attrs.share,+ "data-ai-artifact-id": attrs.id,+ "data-ai-artifact-version": attrs.version,+ "data-ai-artifact-autorun": attrs.autorun,+ "data-ai-artifact-height": attrs.height,+ "data-ai-artifact-width": attrs.width,+ "data-ai-artifact-seamless": attrs.seamless,+ };+ const attributes = Object.entries(dataAttrs)+ .filter(([, value]) => value != null)+ .map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`)+ .join("");+ return `<div class="ai-artifact"${attributes}></div>`;+}++function artifactMarkdown(attrs) {+ return attrs.width != null ||+ (attrs.height != null && normalizedHeight(attrs.height) === null) ||+ (attrs.seamless != null && !["true", "false"].includes(attrs.seamless))+ ? artifactHTML(attrs)+ : compactTag(attrs);+}++/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */+const extension = {+ nodeViews: {+ ai_artifact: { component: AiArtifactNodeView },+ },++ nodeSpec: {+ ai_artifact: {+ attrs: {+ share: { default: null },+ id: { default: null },+ version: { default: null },+ autorun: { default: null },+ height: { default: null },+ width: { default: null },+ seamless: { default: null },+ },+ group: "block",+ atom: true,+ defining: true,+ isolating: true,+ selectable: true,+ createGapCursor: true,+ parseDOM: [+ { tag: "div.ai-artifact", getAttrs: attrsFromDOM },+ { tag: "div.composer-ai-artifact", getAttrs: attrsFromDOM },+ ],+ toDOM(node) {+ const attrs = node.attrs;+ const dataAttrs = {+ class: "composer-ai-artifact",+ contenteditable: "false",+ "data-ai-artifact-share-key": attrs.share,+ "data-ai-artifact-id": attrs.id,+ "data-ai-artifact-version": attrs.version,+ "data-ai-artifact-autorun": attrs.autorun,+ "data-ai-artifact-height": attrs.height,+ "data-ai-artifact-width": attrs.width,+ "data-ai-artifact-seamless": attrs.seamless,+ };+ return ["div", dataAttrs, artifactMarkdown(attrs)];+ },+ },+ },++ parse: {+ ai_artifact(state, token) {+ const { legacy, ...attrs } = token.meta || {};+ const identity = normalizeIdentity({+ ...attrs,+ autorun:+ legacy && attrs.autorun != null+ ? ["", "1", "true"].includes(attrs.autorun)+ ? "true"+ : "false"+ : attrs.autorun,+ });+ if (identity) {+ state.addNode(state.schema.nodes.ai_artifact, {+ ...identity,+ height: attrs.height ?? null,+ width: attrs.width ?? null,+ seamless: attrs.seamless ?? null,+ });+ }+ return true;+ },+ },++ serializeNode: {+ ai_artifact(state, node) {+ state.write(artifactMarkdown(node.attrs));+ state.closeBlock(node);+ },+ },++ inputRules: ({ schema }) => ({+ match: /^\[ai-artifact(?:[ \t]+[a-z]+="[^"\r\n]*")+\]$/,+ handler(state, match, start, end) {+ const attrs = parseTag(match[0]);+ if (!attrs) {+ return null;+ }+ return state.tr.replaceWith(+ start - 1,+ end,+ schema.nodes.ai_artifact.create(attrs)+ );+ },+ }),+ plugins: ({ pmState: { Plugin }, pmModel: { Slice, Fragment }, schema }) =>+ new Plugin({+ props: {+ transformPasted(slice, view) {+ const { $from } = view.state.selection;+ if (+ $from.parent.type.name !== "paragraph" ||+ $from.parent.content.size !== 0 ||+ view.state.storedMarks?.some((mark) => mark.type.name === "code")+ ) {+ return slice;+ }++ const paragraph = slice.content.firstChild;+ if (+ slice.content.childCount !== 1 ||+ paragraph?.type.name !== "paragraph" ||+ paragraph.childCount !== 1 ||+ !paragraph.firstChild.isText ||+ paragraph.firstChild.marks.length+ ) {+ return slice;+ }++ const attrs = parseTag(paragraph.textContent);+ return attrs+ ? new Slice(+ Fragment.from(schema.nodes.ai_artifact.create(attrs)),+ 0,+ 0+ )+ : slice;+ },+ },+ }),+};++export default extension;diff --git a/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-ai-artifacts.js b/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-ai-artifacts.jsnew file mode 100644index 00000000000..ed8b3ec4290--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-ai-artifacts.js@@ -0,0 +1,28 @@+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";++export default class UserActivitySharedAiArtifacts extends DiscourseRoute {+ @service currentUser;+ @service router;+ @service siteSettings;++ beforeModel() {+ if (+ !this.siteSettings.discourse_ai_enabled ||+ !this.currentUser ||+ this.modelFor("user")?.id !== this.currentUser.id+ ) {+ return this.router.replaceWith("userActivity.index");+ }+ }++ model() {+ return ajax("/discourse-ai/ai-bot/artifact-shares.json");+ }++ titleToken() {+ return i18n("discourse_ai.ai_artifact.shared_artifacts");+ }+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-ai-conversations.js b/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-ai-conversations.jsnew file mode 100644index 00000000000..00856ef73fd--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-ai-conversations.js@@ -0,0 +1,28 @@+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";++export default class UserActivitySharedAiConversations extends DiscourseRoute {+ @service currentUser;+ @service router;+ @service siteSettings;++ beforeModel() {+ if (+ !this.siteSettings.discourse_ai_enabled ||+ !this.currentUser ||+ this.modelFor("user")?.id !== this.currentUser.id+ ) {+ return this.router.replaceWith("userActivity.index");+ }+ }++ model() {+ return ajax("/discourse-ai/ai-bot/shared-ai-conversations.json");+ }++ titleToken() {+ return i18n("discourse_ai.shared_ai_conversations.title");+ }+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-artifacts.js b/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-artifacts.jsnew file mode 100644index 00000000000..6c5381d85b6--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/routes/user-activity/shared-artifacts.js@@ -0,0 +1,14 @@+import { service } from "@ember/service";+import SharedAiArtifacts from "./shared-ai-artifacts";++export default class UserActivitySharedArtifacts extends SharedAiArtifacts {+ @service router;++ beforeModel() {+ const redirect = super.beforeModel(...arguments);+ if (redirect) {+ return redirect;+ }+ return this.router.replaceWith("userActivity.sharedAiArtifacts");+ }+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/templates/user-activity/shared-ai-artifacts.gjs b/plugins/discourse-ai/assets/javascripts/discourse/templates/user-activity/shared-ai-artifacts.gjsnew file mode 100644index 00000000000..b05cf02bc26--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/templates/user-activity/shared-ai-artifacts.gjs@@ -0,0 +1,3 @@+import SharedArtifactsList from "../../components/shared-artifacts-list";++export default <template><SharedArtifactsList @data={{@model}} /></template>diff --git a/plugins/discourse-ai/assets/javascripts/discourse/templates/user-activity/shared-ai-conversations.gjs b/plugins/discourse-ai/assets/javascripts/discourse/templates/user-activity/shared-ai-conversations.gjsnew file mode 100644index 00000000000..6c4be650952--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/templates/user-activity/shared-ai-conversations.gjs@@ -0,0 +1,3 @@+import SharedConversationsList from "../../components/shared-conversations-list";++export default <template><SharedConversationsList @data={{@model}} /></template>diff --git a/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tags.js b/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tags.jsindex 12d86c296dc..c64d09372c3 100644--- a/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tags.js+++ b/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tags.js@@ -1,11 +1,252 @@+const TAG_PATTERN = /^\[ai-artifact((?:[ \t]+[a-z]+="[^"\r\n]*")+)\]$/;+const ATTRIBUTE_PATTERN = /[ \t]+([a-z]+)="([^"\r\n]*)"/g;+const SHARE_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;+const DECIMAL_PATTERN = /^[0-9]{1,19}$/;+const HEIGHT_PATTERN = /^[0-9]{1,19}$/;+const LEGACY_DIV_PATTERN = /^<div((?:[ \t]+[a-z-]+="[^"<>]*")+)[ \t]*><\/div>$/;+const LEGACY_ATTR_PATTERN = /[ \t]+([a-z-]+)="([^"<>]*)"/g;+const LEGACY_DATA_ATTRS = [+ "data-ai-artifact-share-key",+ "data-ai-artifact-id",+ "data-ai-artifact-version",+ "data-ai-artifact-autorun",+ "data-ai-artifact-height",+ "data-ai-artifact-width",+ "data-ai-artifact-seamless",+];++function normalizedHeight(value) {+ if (value === undefined || !HEIGHT_PATTERN.test(value)) {+ return value === undefined ? undefined : null;+ }+ const height = Number(value);+ return height > 0 && height <= 2000 ? String(height) : null;+}++function parseArtifact(line) {+ const match = TAG_PATTERN.exec(line);+ if (!match) {+ return;+ }++ const attrs = Object.create(null);+ for (const [, name, value] of match[1].matchAll(ATTRIBUTE_PATTERN)) {+ if (+ !["share", "id", "version", "autorun", "height", "seamless"].includes(+ name+ ) ||+ name in attrs+ ) {+ return;+ }+ attrs[name] = value;+ }++ if (+ attrs.autorun !== undefined &&+ attrs.autorun !== "true" &&+ attrs.autorun !== "false"+ ) {+ return;+ }++ const height = normalizedHeight(attrs.height);+ if (+ height === null ||+ (attrs.seamless !== undefined &&+ attrs.seamless !== "true" &&+ attrs.seamless !== "false")+ ) {+ return;+ }++ if (attrs.share !== undefined) {+ if (+ attrs.id !== undefined ||+ attrs.version !== undefined ||+ !SHARE_PATTERN.test(attrs.share)+ ) {+ return;+ }+ return {+ share: attrs.share,+ autorun: attrs.autorun,+ height,+ seamless: attrs.seamless,+ };+ }++ if (+ !DECIMAL_PATTERN.test(attrs.id || "") ||+ (attrs.version !== undefined && !DECIMAL_PATTERN.test(attrs.version))+ ) {+ return;+ }++ const id = attrs.id.replace(/^0+/, "");+ if (!id) {+ return;+ }++ const version = attrs.version?.replace(/^0+/, "");+ return {+ id,+ version,+ autorun: attrs.autorun,+ height,+ seamless: attrs.seamless,+ };+}++function parseLegacyArtifact(line, unescapeAll) {+ const match = LEGACY_DIV_PATTERN.exec(line);+ if (!match) {+ return;+ }++ const attrs = Object.create(null);+ for (const [, name, value] of match[1].matchAll(LEGACY_ATTR_PATTERN)) {+ if (+ (name !== "class" && !LEGACY_DATA_ATTRS.includes(name)) ||+ name in attrs+ ) {+ return;+ }+ attrs[name] = unescapeAll(value);+ }++ if (attrs.class !== "ai-artifact") {+ return;+ }++ const share = attrs["data-ai-artifact-share-key"];+ const id = attrs["data-ai-artifact-id"];+ const version = attrs["data-ai-artifact-version"];+ if (share !== undefined) {+ if (+ id !== undefined ||+ version !== undefined ||+ !SHARE_PATTERN.test(share)+ ) {+ return;+ }+ } else if (+ !DECIMAL_PATTERN.test(id || "") ||+ (version !== undefined && !DECIMAL_PATTERN.test(version)) ||+ !id.replace(/^0+/, "")+ ) {+ return;+ }++ return {+ legacy: line,+ share,+ id,+ version,+ autorun: attrs["data-ai-artifact-autorun"],+ height: attrs["data-ai-artifact-height"],+ width: attrs["data-ai-artifact-width"],+ seamless: attrs["data-ai-artifact-seamless"],+ };+}++function legacyArtifactBlock(state, startLine, _endLine, silent) {+ if (!state.md.options.discourse.features.aiArtifact) {+ return false;+ }++ const start = state.bMarks[startLine] + state.tShift[startLine];+ const artifact = parseLegacyArtifact(+ state.src.slice(start, state.eMarks[startLine]).trimEnd(),+ state.md.utils.unescapeAll+ );+ if (!artifact) {+ return false;+ }+ if (silent) {+ return true;+ }++ const token = state.push("ai_artifact", "", 0);+ token.block = true;+ token.meta = artifact;+ state.line = startLine + 1;+ return true;+}++function artifactBlock(state, startLine, _endLine, silent) {+ if (!state.md.options.discourse.features.aiArtifact) {+ return false;+ }++ const start = state.bMarks[startLine] + state.tShift[startLine];+ const line = state.src.slice(start, state.eMarks[startLine]).trimEnd();+ const artifact = parseArtifact(line);+ if (!artifact) {+ return false;+ }++ if (silent) {+ return true;+ }++ const token = state.push("ai_artifact", "", 0);+ token.block = true;+ token.meta = artifact;+ state.line = startLine + 1;+ return true;+}+export function setup(helper) {helper.allowList(["details[class=ai-quote]", "details[class=ai-thinking]"]);helper.allowList(["div[class=ai-artifact]","div[data-ai-artifact-id]","div[data-ai-artifact-version]",+ "div[data-ai-artifact-share-key]","div[data-ai-artifact-autorun]","div[data-ai-artifact-height]","div[data-ai-artifact-width]",+ "div[data-ai-artifact-seamless]",]);++ helper.registerOptions((opts, siteSettings) => {+ opts.features.aiArtifact = !!siteSettings.discourse_ai_enabled;+ });++ helper.registerPlugin((md) => {+ md.block.ruler.before(+ "html_block",+ "ai_artifact_legacy",+ legacyArtifactBlock,+ {+ alt: ["paragraph", "reference", "blockquote", "list"],+ }+ );+ md.block.ruler.before("paragraph", "ai_artifact", artifactBlock, {+ alt: ["paragraph", "reference", "blockquote", "list"],+ });+ md.renderer.rules.ai_artifact = (tokens, idx) => {+ const { id, version, share, autorun, height, seamless, legacy } =+ tokens[idx].meta;+ if (legacy) {+ return `${legacy}\n`;+ }+ const heightAttr =+ height !== undefined ? ` data-ai-artifact-height="${height}"` : "";+ const seamlessAttr =+ seamless !== undefined+ ? ` data-ai-artifact-seamless="${seamless}"`+ : "";+ const autorunAttr =+ autorun !== undefined ? ` data-ai-artifact-autorun="${autorun}"` : "";+ if (share) {+ return `<div class="ai-artifact" data-ai-artifact-share-key="${share}"${autorunAttr}${heightAttr}${seamlessAttr}></div>\n`;+ }+ const versionAttr = version+ ? ` data-ai-artifact-version="${version}"`+ : "";+ return `<div class="ai-artifact" data-ai-artifact-id="${id}"${versionAttr}${autorunAttr}${heightAttr}${seamlessAttr}></div>\n`;+ };+ });}diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-artifact.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-artifact.scssindex 8867c45f5e5..505e14cc063 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-artifact.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-artifact.scss@@ -1,3 +1,5 @@+@use "lib/container";+@keyframes artifact-remove {to {height: 0;@@ -145,7 +147,225 @@ html.ai-artifact-expanded {.ai-share-full-topic-modal__body {.ai-artifact-controls {+ display: none;+ }+}++.ai-artifact-share-modal {+ &__link {+ overflow-wrap: anywhere;+ }++ &__actions {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5em;+ }+}++.shared-artifacts,+.shared-conversations {+ container-type: inline-size;+ container-name: ai-shares;++ &__controls {display: flex;+ flex-wrap: wrap;justify-content: space-between;+ align-items: center;+ gap: 0.75em;+ margin-block-end: 1em;+ }++ &__filters {+ display: flex;+ flex-wrap: wrap;+ gap: 0.125em;+ padding: 0.25em;+ background: var(--primary-very-low);+ border-radius: var(--d-border-radius);++ [aria-pressed="true"] {+ background: var(--secondary);+ color: var(--primary);+ font-weight: 600;+ }+ }++ &__list {+ list-style: none;+ padding: 0;+ margin: 0;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ }++ &__card {+ display: grid;+ gap: 1em;+ padding: 1.25em;++ & + & {+ border-block-start: 1px solid var(--primary-low);+ }++ @include container.from(lg, ai-shares) {+ grid-template-columns: minmax(0, 1fr) auto;+ align-items: center;+ }+ }++ &__details {+ min-width: 0;++ h3 {+ margin: 0 0 0.35em;+ font-size: var(--font-up-1);+ overflow-wrap: anywhere;+ }+ }++ &__meta {+ display: flex;+ flex-wrap: wrap;+ gap: 0.35em 0.75em;+ color: var(--primary-medium);+ }++ &__unavailable {+ margin: 0.5em 0 0;+ color: var(--danger);+ }++ &__actions {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ align-items: stretch;+ gap: 0.5em;++ .btn {+ min-height: 2.75rem;+ white-space: normal;++ @include container.until(sm, ai-shares) {+ padding-inline: 0.5em;+ font-size: var(--font-down-1);+ }+ }++ @include container.from(sm, ai-shares) {+ grid-template-columns: repeat(3, minmax(0, 1fr)) minmax(0, 1.5fr);+ }++ @include container.from(lg, ai-shares) {+ grid-template-columns: max-content max-content max-content 16em;+ }+ }++ &__revoke {+ --d-button-danger-text-color: var(--danger);+ --d-button-danger-icon-color: var(--danger);+ --d-button-danger-bg-color: transparent;+ --d-button-danger-text-color--hover: var(--danger);+ --d-button-danger-icon-color--hover: var(--danger);+ --d-button-danger-bg-color--hover: var(--danger-low);++ &:only-child {+ grid-column: 1 / -1;+ }++ @include container.from(sm, ai-shares) {+ &,+ &:only-child {+ grid-column: 4;+ }+ }++ @include container.from(lg, ai-shares) {+ justify-content: flex-start;+ }+ }++ &__empty {+ padding: 1.25em;+ color: var(--primary-medium);+ }++ &__loading {+ display: flex;+ justify-content: center;+ padding: 1em;+ }+}++.shared-conversations {+ &__controls {+ justify-content: flex-end;+ }++ &__card {+ @include container.from(md, ai-shares) {+ grid-template-columns: minmax(0, 1fr) auto;+ align-items: center;+ }+ }++ &__actions {+ @include container.from(sm, ai-shares) {+ grid-template-columns: max-content 16em;+ }+ }++ &__revoke {+ @include container.from(sm, ai-shares) {+ &,+ &:only-child {+ grid-column: 2;+ }+ }+ }+}++.composer-ai-artifact {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75em;+ min-width: 0;+ padding: 0.5em 0.75em;+ border: 1px solid var(--token-color-border-default);+ border-radius: var(--d-border-radius);+ background: var(--token-color-surface);++ &__content {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ &__title {+ overflow: hidden;+ color: var(--token-color-text-default);+ font-weight: var(--token-font-weight-semibold);+ text-overflow: ellipsis;+ white-space: nowrap;++ .d-icon {+ margin-inline-end: 0.4em;+ }+ }++ &__options {+ color: var(--token-color-text-subtle);+ font-size: var(--font-down-1);+ display: flex;+ flex-wrap: wrap;+ gap: 0.25em 1em;+ margin: 0;+ padding: 0;+ }++ &__edit {+ flex-shrink: 0;}}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex f8127136710..8a18f13315a 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -1555,9 +1555,75 @@ en:suffix: "in all topics and posts with AI"ai_artifact:+ editor:+ title: "AI artifact"+ edit_options: "Edit options"+ reference: "Reference"+ share_reference_description: "Share key or a shared artifact link from this site."+ source_reference_description: "Source artifact ID."+ version: "Version"+ version_description: "Leave blank for the base artifact."+ autorun: "Run automatically"+ autorun_default_description: "Only applies when artifact security is set to hybrid mode."+ autorun_strict: "This site requires a click to run."+ autorun_lax: "This site runs artifacts automatically."+ height: "Height (px)"+ height_description: "1–2000 pixels. Leave blank for the default height."+ seamless: "Seamless display"+ seamless_description: "Hide the footer when the artifact runs."+ summary_autorun: "Run automatically: %{value}"+ summary_height: "Height: %{value}"+ summary_height_value: "%{height} px"+ summary_seamless: "Seamless: %{value}"+ default: "Default"+ option_on: "On"+ option_off: "Off"+ apply: "Apply"+ invalid_share: "Enter a valid share key or a link to a shared artifact on this site."+ invalid_source: "Enter a positive source artifact ID (up to 19 digits)."+ invalid_version: "Enter a positive version number (up to 19 digits), or leave blank."+ invalid_height: "Enter a height from 1 to 2000 pixels, or leave blank."expand_view_label: "Expand view"collapse_view_label: "Exit Fullscreen (ESC or Back button)"click_to_run_label: "Run Artifact"+ share: "Share"+ privacy_notice: "Anyone with the link can view this version. Your conversation stays private."+ privacy_notice_login_required: "Signed-in users with the link can view this version. Your conversation stays private."+ create_link: "Create link"+ version_label: "Version %{version}"+ copied: "Copied to clipboard"+ copy_link: "Copy link"+ copy_embed: "Copy embed"+ embed_post: "Embed in post"+ embed_post_title: "Copy the code to embed this artifact in a post"+ embed_website: "Embed on website"+ embed_website_title: "Copy the HTML to embed this artifact on a website"+ new_tab: "Show in new tab"+ update_pin: "Update pinned version"+ pin_updated: "Shared version updated"+ revoke: "Revoke link"+ revoke_conversation: "Revoke conversation share"+ confirm_revoke_standalone_title: "Revoke link?"+ confirm_revoke_standalone_message: "This link and its embeds will stop working. This cannot be undone."+ confirm_revoke_conversation_title: "Revoke conversation share?"+ confirm_revoke_conversation_message: "This permanently stops the shared conversation and its artifact embeds. Standalone links are not revoked."+ shared_artifacts: "Shared AI artifacts"+ filter_shares: "Filter shares"+ filter_all: "All"+ filter_standalone: "Standalone"+ filter_conversation: "Conversation"+ standalone: "Standalone share"+ conversation: "Shared with conversation"+ empty_shares: "No shared AI artifacts yet."+ unavailable: "This link is no longer available. You can still revoke it."+ retry_loading: "Retry loading"+ newest_first: "Newest first"+ oldest_first: "Oldest first"++ shared_ai_conversations:+ title: "Shared AI conversations"+ empty: "No shared AI conversations yet."+ unavailable: "This conversation link is no longer available. You can still revoke it."ai_bot:title: "AI bot"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 4c0415cee90..5bb583b4516 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -309,6 +309,8 @@ en:view_dashboard: "Explore all subjects and questions on the dashboard"disclaimer: "AI-generated observations describe the questions asked, not the quality or helpfulness of their answers. Suggested follow-ups are possibilities to investigate, not confirmed gaps. Questions can appear in multiple subjects."ai_artifact:+ share_version_conflict: "This link already publishes a different version. Refresh and choose Update pinned version to change it."+ uploads_cannot_be_shared: "This artifact references uploads that may be private. Remove the upload references before publishing a standalone link."errors:max_keys_exceeded:one: "You can only have %{count} key in the artifact."diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rbindex 2d0d860c008..9f74c7e2344 100644--- a/plugins/discourse-ai/config/routes.rb+++ b/plugins/discourse-ai/config/routes.rb@@ -43,6 +43,7 @@ DiscourseAi::Engine.routes.draw doendscope module: :ai_bot, path: "/ai-bot/shared-ai-conversations" do+ get "/" => "shared_ai_conversations#index"post "/" => "shared_ai_conversations#create"delete "/:share_key" => "shared_ai_conversations#destroy"get "/:share_key" => "shared_ai_conversations#show"@@ -56,7 +57,27 @@ DiscourseAi::Engine.routes.draw doput "/:topic_id/starred" => "conversations#update_starred"end+ scope module: :ai_bot, path: "/ai-bot/artifact-shares" do+ get "/" => "artifact_shares#index"+ get "/eligibility/:id" => "artifact_shares#eligibility"+ post "/:id" => "artifact_shares#create"+ put "/:share_key" => "artifact_shares#update"+ delete "/:share_key" => "artifact_shares#destroy"+ get "/:share_key/metadata" => "artifacts#shared_metadata", :defaults => { format: :json }+ get "/:share_key/forum" => "artifacts#forum"+ get "/:share_key" => "artifacts#shared"+ end++ scope module: :ai_bot, path: "/ai-bot/artifact-share-key-values/:share_key" do+ get "/" => "artifact_share_key_values#index"+ post "/" => "artifact_share_key_values#set"+ delete "/" => "artifact_share_key_values#destroy"+ end+scope module: :ai_bot, path: "/ai-bot/artifacts" do+ get "/:id/metadata" => "artifacts#metadata", :defaults => { format: :json }+ get "/:id/embed" => "artifacts#embed"+ get "/:id/:version/embed" => "artifacts#embed"get "/:id" => "artifacts#show"get "/:id/:version" => "artifacts#show"enddiff --git a/plugins/discourse-ai/db/migrate/20260922233925_create_ai_artifact_shares.rb b/plugins/discourse-ai/db/migrate/20260922233925_create_ai_artifact_shares.rbnew file mode 100644index 00000000000..93ea895016d--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260922233925_create_ai_artifact_shares.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++class CreateAiArtifactShares < ActiveRecord::Migration[8.0]+ def change+ create_table :ai_artifact_shares do |table|+ table.bigint :ai_artifact_id, null: false+ table.integer :user_id, null: false+ table.string :share_key, null: false+ table.string :name, null: false+ table.integer :version_number, null: false, default: 0+ table.string :html, limit: 65_535+ table.string :css, limit: 65_535+ table.string :js, limit: 65_535+ table.timestamps+ end++ add_index :ai_artifact_shares, :share_key, unique: true+ add_index :ai_artifact_shares, %i[user_id created_at]+ add_index :ai_artifact_shares, %i[user_id ai_artifact_id], unique: true+ add_index :ai_artifact_shares, :ai_artifact_id+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20261008005940_create_ai_artifact_share_key_values.rb b/plugins/discourse-ai/db/migrate/20261008005940_create_ai_artifact_share_key_values.rbnew file mode 100644index 00000000000..2cfdf281b19--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20261008005940_create_ai_artifact_share_key_values.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++class CreateAiArtifactShareKeyValues < ActiveRecord::Migration[8.1]+ def change+ create_table :ai_artifact_share_key_values do |table|+ table.bigint :ai_artifact_share_id, null: false+ table.integer :user_id, null: false+ table.string :key, null: false, limit: 50+ table.string :value, null: false, limit: 20_000+ table.boolean :public, null: false, default: false+ table.timestamps+ end++ add_index :ai_artifact_share_key_values, :user_id+ add_index :ai_artifact_share_key_values,+ %i[ai_artifact_share_id user_id key],+ unique: true,+ name: "index_ai_artifact_share_kv_unique"+ end+enddiff --git a/plugins/discourse-ai/lib/agents/tools/create_artifact.rb b/plugins/discourse-ai/lib/agents/tools/create_artifact.rbindex be02a85b571..f0a29d80a0d 100644--- a/plugins/discourse-ai/lib/agents/tools/create_artifact.rb+++ b/plugins/discourse-ai/lib/agents/tools/create_artifact.rb@@ -356,7 +356,7 @@ module DiscourseAi[/details]### Preview- <div class="ai-artifact" data-ai-artifact-id="#{artifact.id}"></div>+ [ai-artifact id="#{artifact.id}"]MDself.custom_raw = html_previewdiff --git a/plugins/discourse-ai/lib/agents/tools/read_artifact.rb b/plugins/discourse-ai/lib/agents/tools/read_artifact.rbindex fa4dfbb4b97..328e03d15cd 100644--- a/plugins/discourse-ai/lib/agents/tools/read_artifact.rb+++ b/plugins/discourse-ai/lib/agents/tools/read_artifact.rb@@ -191,11 +191,11 @@ module DiscourseAienddef update_custom_html(artifact)- self.custom_raw = <<~HTML+ self.custom_raw = <<~MD### Artifact created successfully- <div class="ai-artifact" data-ai-artifact-id="#{artifact.id}"></div>- HTML+ [ai-artifact id="#{artifact.id}"]+ MDenddef fetch_page(uri)diff --git a/plugins/discourse-ai/lib/agents/tools/update_artifact.rb b/plugins/discourse-ai/lib/agents/tools/update_artifact.rbindex 33092088eb1..b50ce91809b 100644--- a/plugins/discourse-ai/lib/agents/tools/update_artifact.rb+++ b/plugins/discourse-ai/lib/agents/tools/update_artifact.rb@@ -238,7 +238,7 @@ module DiscourseAicontent << [nil, "[/details]"]content << [:preview,- "### Preview\n\n<div class=\"ai-artifact\" data-ai-artifact-version=\"#{new_version.version_number}\" data-ai-artifact-id=\"#{artifact.id}\"></div>",+ "### Preview\n\n[ai-artifact id=\"#{artifact.id}\" version=\"#{new_version.version_number}\"]",]self.custom_raw = content.map { |c| c[1] }.join("\n\n")diff --git a/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rb b/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rbnew file mode 100644index 00000000000..763b2d68424--- /dev/null+++ b/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rb@@ -0,0 +1,281 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ArtifactSharesQuery+ FEED_PAGE_SIZE = 20+ MAX_CONVERSATION_SCAN = 100+ FEED_TYPES = %w[all standalone conversation].freeze+ FEED_ORDERS = %w[newest oldest].freeze++ def initialize(user:, type:, order:, cursor:)+ @user = user+ @type = type.nil? ? "all" : type+ @order = order.nil? ? "newest" : order+ @raw_cursor = cursor+ end++ def call+ raise Discourse::InvalidParameters.new(:type) if !FEED_TYPES.include?(@type)+ raise Discourse::InvalidParameters.new(:order) if !FEED_ORDERS.include?(@order)++ filter = @type+ order = @order+ cursor = parse_feed_cursor(@raw_cursor, filter, order) if !@raw_cursor.nil?++ streams = {}+ if filter != "conversation"+ streams["standalone"] = {+ scope: AiArtifactShare.where(user: @user),+ rows: [],+ cards: {+ },+ after: cursor,+ }+ end+ if filter != "standalone"+ streams["conversation"] = {+ scope: SharedAiConversation.where(user: @user, target_type: "Topic"),+ rows: [],+ cards: {+ },+ after: cursor,+ }+ end++ items = []+ conversation_scans = 0+ last_event = nil+ loop do+ streams.each do |type, stream|+ if stream[:rows].empty? && !stream[:exhausted]+ batch_size = FEED_PAGE_SIZE+ if type == "conversation"+ batch_size = [batch_size, MAX_CONVERSATION_SCAN - conversation_scans].min+ end+ load_feed_batch(stream, type, order, batch_size)+ end+ end+ available =+ streams.filter_map { |type, stream| [type, stream[:rows].first] if stream[:rows].any? }+ break if available.empty?++ type, event =+ if order == "newest"+ available.max_by { |event_type, record| [record.created_at, record.id, event_type] }+ else+ available.min_by { |event_type, record| [record.created_at, record.id, event_type] }+ end+ break if type == "conversation" && conversation_scans == MAX_CONVERSATION_SCAN++ stream = streams[type]+ stream[:rows].shift+ items.concat(stream[:cards].fetch(event.id))+ conversation_scans += 1 if type == "conversation"+ last_event = feed_position(event, type)+ break if items.length >= FEED_PAGE_SIZE || conversation_scans == MAX_CONVERSATION_SCAN+ end++ has_more =+ last_event &&+ streams.any? do |type, stream|+ feed_after(stream[:scope], last_event, type, order).exists?+ end+ {+ items: items,+ has_more: !!has_more,+ next_cursor: has_more ? last_event.merge(order: order, filter: filter) : nil,+ }+ end++ private++ def parse_feed_cursor(raw, filter, order)+ raise Discourse::InvalidParameters.new(:cursor) if !raw.is_a?(String) || raw.bytesize > 512++ value = JSON.parse(raw)+ if !value.is_a?(Hash) || value.keys.sort != %w[created_at filter id order type] ||+ value["filter"] != filter || value["order"] != order ||+ !%w[standalone conversation].include?(value["type"]) ||+ (filter != "all" && value["type"] != filter) || !value["id"].is_a?(Integer) ||+ !value["id"].between?(1, 2**63 - 1) || !value["created_at"].is_a?(String) ||+ !value["created_at"].match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\z/)+ raise Discourse::InvalidParameters.new(:cursor)+ end++ { created_at: Time.iso8601(value["created_at"]), id: value["id"], type: value["type"] }+ rescue JSON::ParserError, ArgumentError+ raise Discourse::InvalidParameters.new(:cursor)+ end++ def feed_position(record, type)+ { created_at: record.created_at.utc.iso8601(6), id: record.id, type: type }+ end++ def feed_after(scope, cursor, type, order)+ return scope if !cursor++ operator = order == "newest" ? "<" : ">"+ inclusive =+ if (type <=> cursor[:type]) == (order == "newest" ? -1 : 1)+ "="+ else+ ""+ end+ scope.where(+ "created_at #{operator} :time OR (created_at = :time AND id #{operator}#{inclusive} :id)",+ time: cursor[:created_at],+ id: cursor[:id],+ )+ end++ def load_feed_batch(stream, type, order, batch_size)+ direction = order == "newest" ? :desc : :asc+ scope = feed_after(stream[:scope], stream[:after], type, order)+ if type == "standalone"+ batch =+ scope+ .includes(:ai_artifact)+ .order(created_at: direction, id: direction)+ .limit(batch_size)+ .to_a+ viewable_posts = viewable_post_ids(batch)+ policy_allows_viewing = AiArtifactShare.publicly_viewable_by?(@user)+ stream[:cards] = batch.to_h do |share|+ [+ share.id,+ [+ {+ id: "standalone-#{share.id}",+ type: "standalone",+ name: share.name,+ share_key: share.share_key,+ url: share.url,+ version: share.version_number,+ created_at: share.created_at,+ available:+ SiteSetting.ai_artifact_security.in?(%w[lax hybrid strict]) &&+ policy_allows_viewing && viewable_posts.include?(share.ai_artifact&.post_id),+ },+ ],+ ]+ end+ else+ batch =+ scope.includes(:user).order(created_at: direction, id: direction).limit(batch_size).to_a+ stream[:cards] = conversation_feed_cards(batch)+ end+ stream[:rows] = batch+ stream[:after] = feed_position(batch.last, type) if batch.any?+ stream[:exhausted] = batch.length < batch_size+ end++ def conversation_feed_cards(batch)+ candidates =+ batch.select do |conversation|+ conversation.context.any? do |context_post|+ context_post["cooked"].to_s.match?(/data-(?:ai-)?artifact-id/i)+ end+ end+ topics_by_id =+ Topic.includes(:category).where(id: candidates.map(&:target_id).uniq).index_by(&:id)+ context_post_ids =+ candidates+ .flat_map do |conversation|+ conversation.context.filter_map { |context_post| context_post["id"] }+ end+ .uniq+ posts_by_id =+ Post+ .includes(topic: :category)+ .where(id: context_post_ids, topic_id: topics_by_id.keys)+ .index_by(&:id)+ visible =+ candidates.select do |conversation|+ topic = topics_by_id[conversation.target_id]+ topic && conversation.publicly_visible?(topic: topic, posts_by_id: posts_by_id)+ end+ artifact_versions_by_conversation =+ visible.to_h do |conversation|+ cooked =+ conversation.context.map { |context_post| context_post["cooked"].to_s }.join("\n")+ versions =+ Nokogiri::HTML5+ .fragment(cooked)+ .css("[data-artifact-id], [data-ai-artifact-id]")+ .filter_map do |node|+ id = (node["data-artifact-id"] || node["data-ai-artifact-id"]).to_i+ next if id <= 0++ version = node["data-artifact-version"] || node["data-ai-artifact-version"]+ version_number = version&.to_i+ [id, version_number&.positive? ? version_number : nil]+ end+ .to_h+ [conversation.id, versions]+ end+ artifact_ids = artifact_versions_by_conversation.values.flat_map(&:keys).uniq+ artifacts_by_id =+ if artifact_ids.empty?+ {}+ else+ AiArtifact+ .joins(:post)+ .where(id: artifact_ids)+ .pluck(+ "ai_artifacts.id",+ "ai_artifacts.name",+ "posts.topic_id",+ "posts.id",+ "ai_artifacts.metadata",+ )+ .index_by(&:first)+ end++ batch.to_h do |conversation|+ cards =+ artifact_versions_by_conversation+ .fetch(conversation.id, {})+ .filter_map do |artifact_id, version|+ artifact = artifacts_by_id[artifact_id]+ next if !artifact || artifact[2] != conversation.target_id++ {+ id: "conversation-#{conversation.id}-#{artifact_id}",+ type: "conversation",+ name: artifact[1],+ url: conversation.url,+ embed_url: AiArtifact.embed_url(artifact_id, version),+ available:+ SiteSetting.ai_artifact_security.in?(%w[lax hybrid strict]) &&+ SiteSetting.discourse_ai_enabled && artifact[4]&.dig("public") == true &&+ posts_by_id.key?(artifact[3]) &&+ conversation.context.any? do |context_post|+ context_post["id"] == artifact[3]+ end,+ artifact_id: artifact_id,+ artifact_version: version,+ share_key: conversation.share_key,+ topic_id: conversation.target_id,+ created_at: conversation.created_at,+ }+ end+ [conversation.id, cards]+ end+ end++ # A snapshot can outlive the post or topic it came from; those links stay+ # listed for revocation, but the profile must not present them as working.+ def viewable_post_ids(shares)+ post_ids = shares.filter_map { |share| share.ai_artifact&.post_id }.uniq+ return Set.new if post_ids.empty?++ posts_by_id = Post.where(id: post_ids).pluck(:id, :topic_id).to_h+ viewable_topic_ids = Topic.where(id: posts_by_id.values.uniq).pluck(:id).to_set+ posts_by_id+ .filter_map { |post_id, topic_id| post_id if viewable_topic_ids.include?(topic_id) }+ .to_set+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rb b/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rbnew file mode 100644index 00000000000..8a068e15ea1--- /dev/null+++ b/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rb@@ -0,0 +1,89 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class SharedConversationsQuery+ PAGE_SIZE = 20+ ORDERS = %w[newest oldest].freeze++ def initialize(user:, order:, cursor:)+ @user = user+ @order = order.nil? ? "newest" : order+ @raw_cursor = cursor+ end++ def call+ raise Discourse::InvalidParameters.new(:order) if !ORDERS.include?(@order)++ cursor = parse_cursor(@raw_cursor) if !@raw_cursor.nil?+ direction = @order == "newest" ? :desc : :asc+ scope = SharedAiConversation.where(user: @user, target_type: "Topic")+ if cursor+ operator = @order == "newest" ? "<" : ">"+ scope =+ scope.where(+ "created_at #{operator} :time OR (created_at = :time AND id #{operator} :id)",+ time: cursor[:created_at],+ id: cursor[:id],+ )+ end++ rows =+ scope+ .includes(:user)+ .order(created_at: direction, id: direction)+ .limit(PAGE_SIZE + 1)+ .to_a+ has_more = rows.length > PAGE_SIZE+ page = rows.first(PAGE_SIZE)+ items = build_items(page)+ { items: items, has_more: has_more, next_cursor: has_more ? position(page.last) : nil }+ end++ private++ def parse_cursor(raw)+ raise Discourse::InvalidParameters.new(:cursor) if !raw.is_a?(String) || raw.bytesize > 512++ value = JSON.parse(raw)+ if !value.is_a?(Hash) || value.keys.sort != %w[created_at id order] ||+ value["order"] != @order || !value["id"].is_a?(Integer) ||+ !value["id"].between?(1, 2**63 - 1) || !value["created_at"].is_a?(String) ||+ !value["created_at"].match?(/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z\z/)+ raise Discourse::InvalidParameters.new(:cursor)+ end++ { created_at: Time.iso8601(value["created_at"]), id: value["id"] }+ rescue JSON::ParserError, ArgumentError+ raise Discourse::InvalidParameters.new(:cursor)+ end++ def position(row)+ { order: @order, created_at: row.created_at.utc.iso8601(6), id: row.id }+ end++ def build_items(page)+ topics_by_id = Topic.includes(:category).where(id: page.map(&:target_id)).index_by(&:id)+ context_post_ids = page.flat_map { |row| row.context.filter_map { |post| post["id"] } }.uniq+ posts_by_id =+ Post+ .includes(topic: :category)+ .where(id: context_post_ids, topic_id: topics_by_id.keys)+ .index_by(&:id)+ page.map do |row|+ topic = topics_by_id[row.target_id]+ available =+ topic.present? && row.publicly_visible?(topic: topic, posts_by_id: posts_by_id)+ {+ id: row.id,+ share_key: row.share_key,+ title: row.title,+ url: row.url,+ created_at: row.created_at,+ available: !!available,+ }+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex 364d1629c3e..09514ee13d7 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -159,6 +159,12 @@ after_initialize doendon(:user_destroyed) do |user|+ AiArtifactKeyValue.where(user_id: user.id).delete_all+ AiArtifactShareKeyValue.where(+ ai_artifact_share_id: AiArtifactShare.where(user_id: user.id).select(:id),+ ).delete_all+ AiArtifactShareKeyValue.where(user_id: user.id).delete_all+ AiArtifactShare.where(user_id: user.id).delete_allDiscourseAi::AiApiAuditLogCleaner.delete_for_user(user.id)DiscourseAi::Discoveries.clear_recent_asks(user_id: user.id)AiAgent.detach_user!(user.id)diff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_artifact_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_artifact_spec.rbindex 2ec0d3b2c3f..21a9e0d100a 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/create_artifact_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_artifact_spec.rb@@ -110,7 +110,7 @@ RSpec.describe DiscourseAi::Agents::Tools::CreateArtifact do[/details]### Preview- <div class="ai-artifact" data-ai-artifact-id="#{artifact_id}"></div>+ [ai-artifact id="#{artifact_id}"]MDexpect(tool.custom_raw.strip).to eq(expected.strip)enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rbindex f50102621c4..b42d050c1ad 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb@@ -40,6 +40,7 @@ RSpec.describe DiscourseAi::Agents::Tools::ReadArtifact doexpect(new_artifact.css).to eq(artifact.css)expect(new_artifact.js).to eq(artifact.js)expect(new_artifact.metadata["cloned_from"]).to eq(artifact.id)+ expect(tool.custom_raw).to include(%([ai-artifact id="#{new_artifact.id}"]))endit "handles invalid URLs" dodiff --git a/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rbindex 511596b1338..9579d34943e 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb@@ -112,7 +112,9 @@ RSpec.describe DiscourseAi::Agents::Tools::UpdateArtifact doexpect(tool.custom_raw).to include("### HTML Changes")expect(tool.custom_raw).to include("### CSS Changes")expect(tool.custom_raw).to include("### JS Changes")- expect(tool.custom_raw).to include("<div class=\"ai-artifact\"")+ expect(tool.custom_raw).to include(+ %([ai-artifact id="#{artifact.id}" version="#{version.version_number}"]),+ )endit "handles partial updates with only some sections" do@@ -369,7 +371,9 @@ RSpec.describe DiscourseAi::Agents::Tools::UpdateArtifact doexpect(tool.custom_raw).to include("[details='View Changes']")expect(tool.custom_raw).to include("### HTML Changes")expect(tool.custom_raw).to include("### CSS Changes")- expect(tool.custom_raw).to include("<div class=\"ai-artifact\"")+ expect(tool.custom_raw).to include(+ %([ai-artifact id="#{artifact.id}" version="#{version.version_number}"]),+ )endit "correctly updates artifact using diff strategy" do@@ -438,6 +442,8 @@ RSpec.describe DiscourseAi::Agents::Tools::UpdateArtifact doexpect(tool.custom_raw).to include("### HTML Changes")expect(tool.custom_raw).to include("### CSS Changes")expect(tool.custom_raw).to include("### JS Changes")- expect(tool.custom_raw).to include("<div class=\"ai-artifact\"")+ expect(tool.custom_raw).to include(+ %([ai-artifact id="#{artifact.id}" version="#{version.version_number}"]),+ )endenddiff --git a/plugins/discourse-ai/spec/lib/ai_artifact_markdown_spec.rb b/plugins/discourse-ai/spec/lib/ai_artifact_markdown_spec.rbnew file mode 100644index 00000000000..c364b4dba4e--- /dev/null+++ b/plugins/discourse-ai/spec/lib/ai_artifact_markdown_spec.rb@@ -0,0 +1,149 @@+# frozen_string_literal: true++RSpec.describe PrettyText do+ before { enable_current_plugin }++ it "cooks compact snapshot and versioned artifact embeds on the server" do+ SiteSetting.ai_artifact_security = "strict"+ share_key = SecureRandom.urlsafe_base64(32)++ cooked =+ PrettyText.cook(+ "[ai-artifact share=\"#{share_key}\"]\n\n[ai-artifact id=\"123\" version=\"2\"]",+ )+ fragment = Nokogiri::HTML5.fragment(cooked)++ expect(+ fragment.css("div.ai-artifact").map { |node| node.attributes.transform_values(&:value) },+ ).to eq(+ [+ { "class" => "ai-artifact", "data-ai-artifact-share-key" => share_key },+ {+ "class" => "ai-artifact",+ "data-ai-artifact-id" => "123",+ "data-ai-artifact-version" => "2",+ },+ ],+ )+ end++ it "cooks explicit autorun booleans on either compact embed form" do+ raw =+ '[ai-artifact share="snapshot-key" autorun="true"]' \+ "\n\n" \+ '[ai-artifact autorun="false" id="123" version="2"]' \+ "\n\n" \+ '[ai-artifact id="456"]'+ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(raw))++ expect(+ fragment.css("div.ai-artifact").map { |node| node.attributes.transform_values(&:value) },+ ).to eq(+ [+ {+ "class" => "ai-artifact",+ "data-ai-artifact-share-key" => "snapshot-key",+ "data-ai-artifact-autorun" => "true",+ },+ {+ "class" => "ai-artifact",+ "data-ai-artifact-id" => "123",+ "data-ai-artifact-version" => "2",+ "data-ai-artifact-autorun" => "false",+ },+ { "class" => "ai-artifact", "data-ai-artifact-id" => "456" },+ ],+ )+ end++ it "keeps malformed autorun attributes inert on the server" do+ invalid_tags = [+ '[ai-artifact share="snapshot-key" autorun="1"]',+ '[ai-artifact id="123" autorun="TRUE"]',+ '[ai-artifact id="123" autorun="true" autorun="false"]',+ '[ai-artifact share="snapshot-key" autorun="false" width="100"]',+ '[ai-artifact id="123" autorun=true]',+ ]+ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(invalid_tags.join("\n\n")))++ expect(fragment.css("div.ai-artifact")).to be_empty+ invalid_tags.each { |tag| expect(fragment.text.tr("“”", '"')).to include(tag) }+ end++ it "cooks compact layout attributes on share and source embeds" do+ raw =+ '[ai-artifact share="snapshot-key" height="2000" seamless="true"]' \+ "\n\n" \+ '[ai-artifact id="123" height="00042" seamless="false"]'+ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(raw))++ expect(+ fragment.css("div.ai-artifact").map { |node| node.attributes.transform_values(&:value) },+ ).to eq(+ [+ {+ "class" => "ai-artifact",+ "data-ai-artifact-share-key" => "snapshot-key",+ "data-ai-artifact-height" => "2000",+ "data-ai-artifact-seamless" => "true",+ },+ {+ "class" => "ai-artifact",+ "data-ai-artifact-id" => "123",+ "data-ai-artifact-height" => "42",+ "data-ai-artifact-seamless" => "false",+ },+ ],+ )+ end++ it "keeps legacy artifact HTML attributes and malformed compact layout inert" do+ raw =+ '<div class="ai-artifact" data-ai-artifact-id="123" data-ai-artifact-seamless="true"></div>' \+ "\n\n" \+ '[ai-artifact id="123" height="2001"]' \+ "\n\n" \+ '[ai-artifact share="key" seamless="1"]'+ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(raw))++ expect(fragment.at_css("div.ai-artifact")["data-ai-artifact-seamless"]).to eq("true")+ expect(fragment.css("div.ai-artifact").length).to eq(1)+ expect(fragment.text.tr("“”", '"')).to include('[ai-artifact id="123" height="2001"]')+ expect(fragment.text.tr("“”", '"')).to include('[ai-artifact share="key" seamless="1"]')+ end++ it "keeps legacy HTML when AI is disabled without parsing compact tags" do+ SiteSetting.discourse_ai_enabled = false+ raw =+ '<div class="ai-artifact" data-ai-artifact-id="123" data-ai-artifact-width="600"></div>' \+ "\n\n" \+ '[ai-artifact id="123" height="2000"]'+ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(raw))++ expect(fragment.css("div.ai-artifact").length).to eq(1)+ expect(fragment.at_css("div.ai-artifact")["data-ai-artifact-width"]).to eq("600")+ expect(fragment.text.tr("“”", '"')).to include('[ai-artifact id="123" height="2000"]')+ end++ it "keeps malformed native artifact identifiers inert on the server" do+ invalid_tags = [+ '[ai-artifact share="snapshot-key" id="123"]',+ '[ai-artifact share="https://example.com/artifact"]',+ '[ai-artifact id="123" id="456"]',+ '[ai-artifact id="0"]',+ ]++ fragment = Nokogiri::HTML5.fragment(PrettyText.cook(invalid_tags.join("\n\n")))++ expect(fragment.css("div.ai-artifact")).to be_empty+ invalid_tags.each { |tag| expect(fragment.text.tr("“”", '"')).to include(tag) }+ end++ it "keeps compact snapshot embeds inside code inert" do+ raw = '[ai-artifact share="snapshot-key"]'+ fragment = Nokogiri::HTML5.fragment(PrettyText.cook("```\n#{raw}\n```"))++ expect(fragment.at_css("code").text.strip).to eq(raw)+ expect(fragment.css("div.ai-artifact")).to be_empty+ end+enddiff --git a/plugins/discourse-ai/spec/models/ai_artifact_share_spec.rb b/plugins/discourse-ai/spec/models/ai_artifact_share_spec.rbnew file mode 100644index 00000000000..ed294783cf2--- /dev/null+++ b/plugins/discourse-ai/spec/models/ai_artifact_share_spec.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true++RSpec.describe AiArtifactShare do+ fab!(:artifact, :ai_artifact)+ fab!(:owner, :user)++ before { enable_current_plugin }++ it "removes published snapshots when the source artifact is destroyed" do+ share =+ described_class.create!(+ ai_artifact: artifact,+ user: owner,+ **described_class.new(ai_artifact: artifact).snapshot_attributes(version_number: 0),+ )++ artifact.destroy!++ expect(described_class.exists?(share.id)).to eq(false)+ end++ it "removes only the destroyed owner's published snapshots" do+ share =+ described_class.create!(+ ai_artifact: artifact,+ user: owner,+ **described_class.new(ai_artifact: artifact).snapshot_attributes(version_number: 0),+ )+ other_share =+ described_class.create!(+ ai_artifact: artifact,+ user: artifact.user,+ **described_class.new(ai_artifact: artifact).snapshot_attributes(version_number: 0),+ )++ UserDestroyer.new(Discourse.system_user).destroy(owner)++ expect(described_class.where(id: [share.id, other_share.id]).pluck(:id)).to eq([other_share.id])+ end++ it "deletes share storage when the source artifact is hard-destroyed" do+ share =+ described_class.create!(+ ai_artifact: artifact,+ user: owner,+ **described_class.new(ai_artifact: artifact).snapshot_attributes(version_number: 0),+ )+ record = share.key_values.create!(user: owner, key: "vote", value: "yes")++ artifact.destroy!++ expect(AiArtifactShareKeyValue.exists?(record.id)).to eq(false)+ end++ it "removes a deleted user's source artifact storage while preserving other users' values" do+ deleted_record = artifact.key_values.create!(user: owner, key: "vote", value: "deleted")+ surviving_record =+ artifact.key_values.create!(user: artifact.user, key: "vote", value: "survives")++ UserDestroyer.new(Discourse.system_user).destroy(owner)++ expect(AiArtifactKeyValue.where(id: [deleted_record.id, surviving_record.id]).pluck(:id)).to eq(+ [surviving_record.id],+ )+ end++ it "cleans up both an owner's share storage and their votes on other shares" do+ share =+ described_class.create!(+ ai_artifact: artifact,+ user: owner,+ **described_class.new(ai_artifact: artifact).snapshot_attributes(version_number: 0),+ )+ other_share =+ described_class.create!(+ ai_artifact: artifact,+ user: artifact.user,+ **described_class.new(ai_artifact: artifact).snapshot_attributes(version_number: 0),+ )+ visitor = Fabricate(:user)+ owned_record = share.key_values.create!(user: visitor, key: "vote", value: "owned")+ visitor_record = other_share.key_values.create!(user: owner, key: "vote", value: "visitor")+ surviving_record = other_share.key_values.create!(user: visitor, key: "vote", value: "survives")++ UserDestroyer.new(Discourse.system_user).destroy(owner)++ expect(+ AiArtifactShareKeyValue.where(+ id: [owned_record.id, visitor_record.id, surviving_record.id],+ ).pluck(:id),+ ).to eq([surviving_record.id])+ end+enddiff --git a/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb b/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rbindex f9efc41f196..a2d91a22eb8 100644--- a/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb+++ b/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb@@ -245,6 +245,122 @@ RSpec.describe SharedAiConversation, type: :model doendend+ describe "#publicly_visible?" do+ let(:visibility_topic) { Fabricate(:private_message_topic, user: user, recipient: agent.user) }+ let!(:visibility_post) { Fabricate(:post, topic: visibility_topic, user: user) }+ let(:conversation) { described_class.share_conversation(user, visibility_topic) }++ before do+ group = Fabricate(:group)+ group.add(user)+ user.reload+ SiteSetting.ai_bot_public_sharing_allowed_groups = group.id.to_s+ end++ it "accepts matching preloaded topics and posts while rejecting unrelated preloads" do+ expect(conversation.publicly_visible?).to eq(true)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ visibility_post.id => visibility_post,+ },+ ),+ ).to eq(true)++ other_topic = Fabricate(:private_message_topic, user: user, recipient: agent.user)+ other_post = Fabricate(:post, topic: other_topic, user: user)+ expect(+ conversation.publicly_visible?(+ topic: other_topic,+ posts_by_id: {+ visibility_post.id => visibility_post,+ },+ ),+ ).to eq(false)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ visibility_post.id => other_post,+ },+ ),+ ).to eq(false)+ same_topic_post = Fabricate(:post, topic: visibility_topic, user: user)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ visibility_post.id => same_topic_post,+ },+ ),+ ).to eq(false)+ end++ it "rejects hidden context posts the source user cannot see" do+ conversation+ visibility_post.update_columns(user_id: agent.user.id, hidden: true)+ expect(user.guardian.can_share_ai_bot_conversation?(visibility_topic)).to eq(true)+ expect(user.guardian.can_see?(visibility_post.reload)).to eq(false)++ expect(conversation.publicly_visible?).to eq(false)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ visibility_post.id => visibility_post,+ },+ ),+ ).to eq(false)+ end++ it "rejects trashed context posts even when supplied as preloaded records" do+ conversation+ visibility_post.trash!++ expect(conversation.publicly_visible?).to eq(false)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ visibility_post.id => visibility_post,+ },+ ),+ ).to eq(false)+ end++ it "rejects context posts belonging to another topic" do+ other_topic = Fabricate(:private_message_topic, user: user, recipient: agent.user)+ other_post = Fabricate(:post, topic: other_topic, user: user)+ conversation.update!(context: [{ id: other_post.id, cooked: other_post.cooked }])++ expect(conversation.publicly_visible?).to eq(false)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ other_post.id => other_post,+ },+ ),+ ).to eq(false)+ end++ it "rejects a trashed topic even when the topic was preloaded before deletion" do+ conversation+ visibility_topic.trash!++ expect(conversation.publicly_visible?).to eq(false)+ expect(+ conversation.publicly_visible?(+ topic: visibility_topic,+ posts_by_id: {+ visibility_post.id => visibility_post,+ },+ ),+ ).to eq(false)+ end+ end+describe "#onebox" doit "escapes title and username" domalicious_username = %(user"><img src=x onerror=alert(1)>)diff --git a/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rbnew file mode 100644index 00000000000..b174ac39632--- /dev/null+++ b/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rb@@ -0,0 +1,1166 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::ArtifactSharesController do+ fab!(:owner) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:llm_model) { Fabricate(:llm_model, name: "artifact-sharing-model") }+ fab!(:agent) { Fabricate(:ai_agent, default_llm: llm_model).tap(&:ensure_user!) }+ fab!(:topic) { Fabricate(:private_message_topic, user: owner) }+ fab!(:source_post) { Fabricate(:post, topic: topic, user: owner) }+ fab!(:artifact) { Fabricate(:ai_artifact, post: source_post, user: owner) }++ let(:base_path) { "/discourse-ai/ai-bot/artifact-shares" }+ let(:bot_user) { agent.user }++ before do+ enable_current_plugin+ SiteSetting.ai_artifact_security = "strict"+ SiteSetting.ai_bot_enabled = true+ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"+ toggle_enabled_bots(bots: [llm_model])+ topic.topic_allowed_users.where.not(user_id: owner.id).delete_all+ topic.topic_allowed_users.create!(user: bot_user)+ Group.user_trust_level_change!(owner.id, owner.trust_level)+ end++ it "keeps the global login wall for a valid standalone share key" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ share.pin!(version_number: 0)+ SiteSetting.login_required = true++ get "#{base_path}/#{share.share_key}"+ expect(response).to redirect_to("/login")+ end++ it "lists disabled shares for revocation, refuses publication, and never revives revoked keys" do+ source_post.update_columns(+ cooked: "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}'></div>",+ )+ conversation = SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]++ SiteSetting.ai_artifact_security = "disabled"+ get "#{base_path}.json"+ expect(response.status).to eq(200)+ expect(+ response.parsed_body["items"].map { |item| [item["type"], item["available"]] },+ ).to contain_exactly(["standalone", false], ["conversation", false])+ get "#{base_path}/eligibility/#{artifact.id}.json"+ expect(response.status).to eq(404)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(404)+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ sign_in(owner)+ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(204)++ SiteSetting.ai_artifact_security = "strict"+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ get "#{base_path}.json"+ expect(response.parsed_body["items"].map { |item| item["type"] }).to eq(["conversation"])+ expect(response.parsed_body["items"].first["available"]).to eq(true)+ expect(response.parsed_body["items"].first["embed_url"]).to eq(+ AiArtifact.embed_url(artifact.id),+ )+ expect(conversation.reload).to be_present+ end++ it "blocks a conversation embed after sharing, group membership, or source visibility is revoked" do+ source_post.update_columns(+ cooked: "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}'></div>",+ )+ conversation = SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(200)++ SiteSetting.ai_bot_public_sharing_allowed_groups = "1"+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"+ group = Fabricate(:group)+ group.add(owner)+ SiteSetting.ai_bot_public_sharing_allowed_groups = group.id.to_s+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(200)+ group.remove(owner)+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"+ topic.topic_allowed_users.create!(user: Fabricate(:user))+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ topic.topic_allowed_users.last.destroy!+ source_post.trash!+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ source_post.recover!+ SharedAiConversation.destroy_conversation(conversation)+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ end++ it "pins the base content for a guest without granting access to ID, versions, or key values" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(201)+ key = response.parsed_body["share_key"]+ pinned_html = artifact.html++ artifact.update!(html: "<p>Private future content</p>")+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.parsed_body["share_key"]).to eq(key)+ expect(response.status).to eq(200)+ future_version = artifact.create_new_version(html: "<p>Private future version</p>")+ sign_out++ get "#{base_path}/#{key}"+ expect(response.status).to eq(200)+ frame = Nokogiri.HTML5(response.body).at_css("iframe")+ expect(frame["sandbox"]).to eq("allow-scripts allow-forms")+ expect(response.headers["Referrer-Policy"]).to eq("no-referrer")+ expect(frame["srcdoc"]).to include(pinned_html)+ expect(frame["srcdoc"]).to include("window.discourseArtifactReady = Promise.resolve")+ expect(frame["srcdoc"]).to include("window.discourseArtifact = {")+ expect(frame["srcdoc"]).to include("Key-value storage is unavailable in public shares")+ expect(frame["srcdoc"]).not_to include("_discourse_user_data", "_postMessageRequest")+ expect(frame["srcdoc"]).not_to include(artifact.html, future_version.html)+ expect(response.body).not_to include(+ "discourse-artifact-kv",+ "csrf-token",+ "_discourse_user_data",+ )++ get artifact.url+ expect(response.status).to eq(404)+ get AiArtifact.url(artifact.id, future_version.version_number)+ expect(response.status).to eq(404)+ get "/discourse-ai/ai-bot/artifact-key-values/#{artifact.id}.json"+ expect(response.status).not_to eq(200)+ end++ it "pins an explicit version and updates only on an owner's explicit request" do+ first = artifact.create_new_version(html: "<p>First version</p>")+ second = artifact.create_new_version(html: "<p>Second version</p>")+ sign_in(owner)++ post "#{base_path}/#{artifact.id}.json", params: { version: first.version_number }+ key = response.parsed_body["share_key"]+ get "#{base_path}/#{key}"+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).to include(first.html)++ put "#{base_path}/#{key}.json", params: { version: second.version_number }+ expect(response.status).to eq(200)+ get "#{base_path}/#{key}"+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).to include(second.html)++ put "#{base_path}/#{key}.json", params: { version: 999 }+ expect(response.status).to eq(404)++ third = artifact.create_new_version(html: "<p>Third version</p>")+ put "#{base_path}/#{key}.json"+ expect(response.status).to eq(404)+ get "#{base_path}/#{key}"+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).to include(second.html)++ put "#{base_path}/#{key}.json", params: { version: first.version_number }+ expect(response.parsed_body["version"]).to eq(first.version_number)+ get "#{base_path}/#{key}"+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).to include(first.html)+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).not_to include(third.html)++ put "#{base_path}/#{key}.json", params: { version: 0 }+ expect(response.parsed_body["version"]).to eq(0)+ end++ it "requires an explicit existing version when creating and updating a link" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json"+ expect(response.status).to eq(404)+ expect(AiArtifactShare.where(ai_artifact: artifact, user: owner)).not_to exist++ post "#{base_path}/#{artifact.id}.json", params: { version: "00" }+ expect(response.status).to eq(404)+ post "#{base_path}/#{artifact.id}.json", params: { version: 999 }+ expect(response.status).to eq(404)+ post "#{base_path}/#{artifact.id}.json", params: { version: "9999999999999999999999999" }+ expect(response.status).to eq(404)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(201)+ expect(response.parsed_body["version"]).to eq(0)+ end++ it "rejects other users and revokes only the standalone link" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ other_user = Fabricate(:user)+ topic.topic_allowed_users.create!(user: other_user)+ sign_in(other_user)++ get "#{base_path}/eligibility/#{artifact.id}.json"+ expect(response.parsed_body["can_share"]).to eq(false)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(404)+ put "#{base_path}/#{key}.json"+ expect(response.status).to eq(404)+ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(404)+ get "#{base_path}.json"+ expect(response.parsed_body["items"]).to eq([])++ sign_in(owner)+ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(204)+ sign_out+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ end++ it "permits the PM creator to share a bot-owned artifact without publishing conversation context" do+ artifact.update!(user: bot_user)+ sign_in(owner)+ get "#{base_path}/eligibility/#{artifact.id}.json"+ expect(response.parsed_body["can_share"]).to eq(true)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(201)+ sign_out+ get "#{base_path}/#{response.parsed_body["share_key"]}"+ expect(response.status).to eq(200)+ expect(response.body).not_to include(source_post.raw)+ end++ it "permits the PM creator to share an artifact owned by a detached legacy bot" do+ legacy_bot = Fabricate(:user, id: DiscourseAi::BotUser.next_id)+ UserCustomField.create!(+ user: legacy_bot,+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,+ value: "true",+ )+ topic.topic_allowed_users.where.not(user_id: owner.id).delete_all+ topic.topic_allowed_users.create!(user: legacy_bot)+ artifact.update!(user: legacy_bot)+ sign_in(owner)++ get "#{base_path}/eligibility/#{artifact.id}.json"+ expect(response.parsed_body["can_share"]).to eq(true)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response).to have_http_status(:created)+ expect(AiArtifactShare.find_by!(ai_artifact: artifact, user: owner).share_key).to eq(+ response.parsed_body["share_key"],+ )+ end++ it "keeps a standalone snapshot after conversation access is revoked" do+ topic.topic_allowed_users.where.not(user_id: owner.id).delete_all+ topic.topic_allowed_users.create!(user: bot_user)+ second_artifact =+ Fabricate(:ai_artifact, user: owner, post: source_post, name: "Another artifact")+ source_post.update_columns(+ cooked:+ "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}'></div>" \+ "<div class='ai-artifact' data-ai-artifact-id='#{second_artifact.id}'></div>",+ )++ conversation = SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ 20.times do |index|+ extra_artifact =+ Fabricate(:ai_artifact, user: owner, post: source_post, name: "Extra #{index}")+ AiArtifactShare.new(ai_artifact: extra_artifact, user: owner).pin!(version_number: 0)+ end+ get "#{base_path}.json"+ expect(response.parsed_body["items"].length).to eq(20)+ expect(response.parsed_body["has_more"]).to eq(true)+ cursor = response.parsed_body["next_cursor"]+ get "#{base_path}.json", params: { cursor: cursor.to_json }+ expect(response.parsed_body["items"].map { |item| item["name"] }).to contain_exactly(+ artifact.name,+ second_artifact.name,+ artifact.name,+ )+ expect(response.parsed_body["items"].map { |item| item["type"] }).to contain_exactly(+ "standalone",+ "conversation",+ "conversation",+ )+ expect(response.parsed_body["has_more"]).to eq(false)++ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(204)+ get conversation.url+ expect(response.status).to eq(200)++ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ delete "/discourse-ai/ai-bot/shared-ai-conversations/#{conversation.share_key}.json"+ expect(response.status).to eq(200)+ get "#{base_path}.json"+ expect(response.parsed_body["items"].map { |item| item["type"] }).to all(eq("standalone"))+ sign_out+ get "#{base_path}/#{key}"+ expect(response.status).to eq(200)+ get artifact.url+ expect(response.status).to eq(404)+ end++ it "paginates the owner's standalone links and rejects access after losing post visibility" do+ sign_in(owner)+ 21.times do |index|+ extra_artifact =+ Fabricate(:ai_artifact, user: owner, post: source_post, name: "Artifact #{index}")+ AiArtifactShare.new(ai_artifact: extra_artifact, user: owner).pin!(version_number: 0)+ end++ get "#{base_path}.json"+ first_page = response.parsed_body+ expect(first_page["items"].length).to eq(20)+ expect(first_page["has_more"]).to eq(true)+ expect(first_page["items"].map { |item| item["id"] }.uniq.length).to eq(20)+ get "#{base_path}.json", params: { cursor: first_page["next_cursor"].to_json }+ expect(response.parsed_body["items"].map { |item| item["name"] }).to eq(["Artifact 0"])+ expect(response.parsed_body["has_more"]).to eq(false)+ expect(response.parsed_body["next_cursor"]).to be_nil+ get "#{base_path}.json", params: { order: "oldest" }+ expect(response.parsed_body["items"].first["name"]).to eq("Artifact 0")+ get "#{base_path}.json", params: { order: "newest" }+ expect(response.parsed_body["items"].first["name"]).to eq("Artifact 20")++ topic.topic_allowed_users.where(user_id: owner.id).delete_all+ topic.trash!+ get "#{base_path}/eligibility/#{artifact.id}.json"+ expect(response.parsed_body["can_share"]).to eq(false)+ end++ it "paginates conversations by conversation rather than by the number of artifact cards" do+ 21.times do |index|+ conversation_topic = Fabricate(:private_message_topic, user: owner, recipient: bot_user)+ conversation_post = Fabricate(:post, topic: conversation_topic, user: owner)+ conversation_artifact =+ Fabricate(:ai_artifact, post: conversation_post, user: owner, name: "Card #{index}")+ conversation_post.update_columns(+ cooked: "<div class='ai-artifact' data-ai-artifact-id='#{conversation_artifact.id}'></div>",+ )+ SharedAiConversation.share_conversation(owner, conversation_topic)+ end+ sign_in(owner)++ queries = track_sql_queries { get "#{base_path}.json", params: { type: "conversation" } }+ expect(queries.size).to be <= 210+ first_page = response.parsed_body+ expect(first_page["items"].length).to eq(20)+ expect(first_page["has_more"]).to eq(true)+ expect(first_page["items"].first["name"]).to eq("Card 20")+ get "#{base_path}.json",+ params: {+ type: "conversation",+ cursor: first_page["next_cursor"].to_json,+ }+ expect(response.parsed_body["items"].map { |item| item["name"] }).to eq(["Card 0"])+ expect(response.parsed_body["has_more"]).to eq(false)+ get "#{base_path}.json", params: { type: "conversation", order: "oldest" }+ expect(response.parsed_body["items"].first["name"]).to eq("Card 0")++ oldest_conversation = SharedAiConversation.where(user: owner).order(:created_at, :id).first+ original_context = oldest_conversation.context+ oldest_conversation.update_columns(+ context: [{ "id" => original_context.first["id"], "cooked" => "No artifact" }],+ )+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].length).to eq(20)+ expect(response.parsed_body["has_more"]).to eq(true)+ get "#{base_path}.json",+ params: {+ type: "conversation",+ cursor: response.parsed_body["next_cursor"].to_json,+ }+ expect(response.parsed_body["items"]).to eq([])+ expect(response.parsed_body["has_more"]).to eq(false)+ oldest_conversation.update_columns(context: original_context)++ SharedAiConversation+ .where(user: owner)+ .order(created_at: :desc, id: :desc)+ .limit(20)+ .each do |conversation|+ conversation.update_columns(+ context: [{ "id" => conversation.context.first["id"], "cooked" => "No artifact" }],+ )+ end+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].map { |item| item["name"] }).to eq(["Card 0"])+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ it "bounds scans of empty conversation snapshots while providing a cursor to later cards" do+ 101.times do |index|+ empty_topic = Fabricate(:private_message_topic, user: owner, recipient: bot_user)+ empty_post = Fabricate(:post, topic: empty_topic, user: owner)+ empty_post.update_columns(cooked: "No artifact #{index}")+ SharedAiConversation.create!(+ user: owner,+ target: empty_topic,+ title: empty_topic.title,+ llm_name: "Bot",+ excerpt: "No artifact",+ context: [{ id: empty_post.id, cooked: empty_post.cooked }],+ )+ end+ source_post.update_columns(+ cooked: "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}'></div>",+ )+ SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)++ queries =+ track_sql_queries do+ get "#{base_path}.json", params: { type: "conversation", order: "oldest" }+ end+ expect(queries.size).to be <= 40+ first_page = response.parsed_body+ expect(first_page["items"]).to eq([])+ expect(first_page["has_more"]).to eq(true)+ expect(first_page["next_cursor"]["id"]).to eq(+ SharedAiConversation.where(user: owner).order(:created_at, :id).limit(100).last.id,+ )++ get "#{base_path}.json",+ params: {+ type: "conversation",+ order: "oldest",+ cursor: first_page["next_cursor"].to_json,+ }+ expect(response.parsed_body["items"].map { |card| card["name"] }).to eq([artifact.name])+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ it "lists artifact cards from multiple posts in one conversation" do+ second_artifact = Fabricate(:ai_artifact, post: source_post, user: owner, name: "Second card")+ second_post = Fabricate(:post, topic: topic, user: owner)+ artifact.update!(post: second_post)+ source_post.update_columns(cooked: "<div data-ai-artifact-id='#{second_artifact.id}'></div>")+ second_post.update_columns(cooked: "<div data-ai-artifact-id='#{artifact.id}'></div>")+ SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)++ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].map { |card| card["name"] }).to contain_exactly(+ second_artifact.name,+ artifact.name,+ )+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ it "lists one card per artifact when a conversation references multiple versions" do+ pinned = artifact.create_new_version(html: "<p>Pinned version</p>")+ source_post.update_columns(+ cooked:+ "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}'></div>" \+ "<div class='ai-artifact' data-artifact-id='#{artifact.id}' data-artifact-version='0'></div>" \+ "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}' data-ai-artifact-version='#{pinned.version_number}'></div>",+ )+ conversation = SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)++ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].map { |card| card["id"] }).to eq(+ ["conversation-#{conversation.id}-#{artifact.id}"],+ )+ card = response.parsed_body["items"].first+ expect(card["share_key"]).to eq(conversation.share_key)+ expect(card["url"]).to eq(conversation.url)+ expect(card["embed_url"]).to eq(AiArtifact.embed_url(artifact.id, pinned.version_number))+ expect(card.slice("artifact_id", "artifact_version")).to eq(+ "artifact_id" => artifact.id,+ "artifact_version" => pinned.version_number,+ )+ expect(response.parsed_body.to_json).not_to include("preview_url")++ sign_out+ get card["embed_url"]+ expect(response.status).to eq(200)+ expect(response.headers["X-Frame-Options"]).to be_nil+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).to include(pinned.html)+ end++ it "hides expanded private conversations while retaining a previously published snapshot" do+ source_post.update_columns(cooked: "<div data-ai-artifact-id='#{artifact.id}'></div>")+ SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]++ topic.topic_allowed_users.create!(user: Fabricate(:user))+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"]).to eq([])+ get "#{base_path}.json", params: { type: "standalone" }+ expect(response.parsed_body["items"].map { |item| item["share_key"] }).to eq([key])++ sign_out+ get "#{base_path}/#{key}"+ expect(response.status).to eq(200)+ end++ it "omits conversation cards when a context post is hidden, trashed, or belongs to another topic" do+ source_post.update_columns(cooked: "<div data-ai-artifact-id='#{artifact.id}'></div>")+ conversation = SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)++ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].map { |card| card["name"] }).to eq([artifact.name])++ source_post.update_columns(user_id: bot_user.id, hidden: true)+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"]).to eq([])++ source_post.update_columns(user_id: owner.id, hidden: false)+ source_post.trash!+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"]).to eq([])++ source_post.recover!+ other_topic = Fabricate(:private_message_topic, user: owner, recipient: bot_user)+ other_post = Fabricate(:post, topic: other_topic, user: owner)+ conversation.update_columns(context: [{ id: other_post.id, cooked: source_post.cooked }])+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"]).to eq([])+ end++ it "rejects a different requested version on create without changing the published snapshot" do+ version = artifact.create_new_version(html: "<p>Different version</p>")+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]++ post "#{base_path}/#{artifact.id}.json", params: { version: version.version_number }+ expect(response.status).to eq(409)+ expect(response.parsed_body["error"]).to eq(+ I18n.t("discourse_ai.ai_artifact.share_version_conflict"),+ )+ expect(AiArtifactShare.find_by!(share_key: key).version_number).to eq(0)+ end++ it "returns the existing link if another request creates it first" do+ existing = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ existing.pin!(version_number: 0)+ expect(AiArtifactShare.where(ai_artifact: artifact, user: owner).count).to eq(1)+ sign_in(owner)++ AiArtifactShare.stubs(:find_by).returns(nil, existing)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(200)+ expect(response.parsed_body["share_key"]).to eq(existing.share_key)+ expect(AiArtifactShare.where(ai_artifact: artifact, user: owner).count).to eq(1)+ end++ it "rejects restricted topics, multi-person PMs, and users outside the allowed groups" do+ sign_in(owner)+ group = Fabricate(:group)+ group.add(owner)+ restricted_category = Fabricate(:private_category, group: group)+ restricted_topic = Fabricate(:topic, user: owner, category: restricted_category)+ restricted_post = Fabricate(:post, topic: restricted_topic, user: owner)+ restricted_artifact = Fabricate(:ai_artifact, post: restricted_post, user: owner)+ expect(owner.guardian.can_see?(restricted_post)).to eq(true)+ post "#{base_path}/#{restricted_artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(404)++ SiteSetting.ai_bot_public_sharing_allowed_groups = "1"+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"++ topic.topic_allowed_users.create!(user: Fabricate(:user))+ get "#{base_path}/eligibility/#{artifact.id}.json"+ expect(response.parsed_body["can_share"]).to eq(false)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(404)+ end++ it "refuses to repin an existing share when the owner's group or PM eligibility changes" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ version = artifact.create_new_version(html: "<p>Not published</p>")++ SiteSetting.ai_bot_public_sharing_allowed_groups = "1"+ put "#{base_path}/#{key}.json", params: { version: version.version_number }+ expect(response.status).to eq(404)++ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"+ topic.topic_allowed_users.create!(user: Fabricate(:user))+ put "#{base_path}/#{key}.json", params: { version: version.version_number }+ expect(response.status).to eq(404)+ expect(AiArtifactShare.find_by!(share_key: key).version_number).to eq(0)+ end++ it "rejects an artifact owned by another human even when the PM creator can share the conversation" do+ artifact.update!(user: Fabricate(:user))+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(404)+ end++ it "rejects private upload references in any pinned version without changing the existing share" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ version = artifact.create_new_version(html: '<img src="/secure-uploads/private.png">')++ put "#{base_path}/#{key}.json", params: { version: version.version_number }+ expect(response.status).to eq(403)+ expect(response.parsed_body["errors"]).to include(+ I18n.t("discourse_ai.ai_artifact.uploads_cannot_be_shared"),+ )+ expect(AiArtifactShare.find_by!(share_key: key).version_number).to eq(0)++ artifact.update!(css: 'background: url("upload://private");')+ extra =+ Fabricate(+ :ai_artifact,+ post: source_post,+ user: owner,+ html: '<img src="/uploads/default/original/1X/secret.png">',+ )+ post "#{base_path}/#{extra.id}.json", params: { version: 0 }+ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: extra)).not_to exist+ end++ it "rejects HTML entity-encoded upload references in a snapshot" do+ artifact.update!(html: '<img src="/secure-uploads/private.png">')+ sign_in(owner)++ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist++ artifact.update!(html: "<p>Safe HTML</p>", css: "url(upload://private)")+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist+ end++ it "rejects legacy secure upload URLs in snapshots" do+ sign_in(owner)+ artifact.update!(html: '<img src="/secure-media-uploads/original/1X/private.png">')++ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }++ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist+ end++ it "rejects upload CDN URLs when the configured root ends in a slash" do+ SiteSetting.Upload.stubs(:enable_s3_uploads).returns(true)+ SiteSetting.Upload.stubs(:s3_base_url).returns("//uploads-bucket.s3.example.com/forum")+ SiteSetting.Upload.stubs(:s3_cdn_url).returns("https://uploads-cdn.example.com/forum/")+ sign_in(owner)+ artifact.update!(html: '<img src="//uploads-cdn.example.com/forum/original/private.png">')++ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }++ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist+ end++ it "rejects configured S3 and CDN upload roots in snapshots" do+ SiteSetting.Upload.stubs(:enable_s3_uploads).returns(true)+ SiteSetting.Upload.stubs(:s3_base_url).returns("//uploads-bucket.s3.example.com/forum")+ SiteSetting.Upload.stubs(:s3_cdn_url).returns("https://uploads-cdn.example.com/forum")+ sign_in(owner)++ artifact.update!(+ html: '<img src="https://uploads-bucket.s3.example.com/forum/original/private.png">',+ )+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist++ artifact.update!(+ html: "<p>Safe HTML</p>",+ js: 'fetch("//uploads-cdn.example.com/forum/original/private.png")',+ )+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).to eq(403)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist+ end++ it "stops serving a share if its source or owner is removed" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ source_post.trash!+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ source_post.recover!++ topic.trash!+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ topic.recover!++ share = AiArtifactShare.find_by!(share_key: key)+ share.update_columns(user_id: 2_000_000_000)+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ share.update_columns(user_id: owner.id)++ DiscourseEvent.trigger(:user_destroyed, owner)+ expect(AiArtifactShare.where(share_key: key)).not_to exist+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ end++ it "stops serving a published snapshot once sharing settings or group membership change" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ sign_out++ get "#{base_path}/#{key}"+ expect(response.status).to eq(200)++ SiteSetting.ai_bot_enabled = false+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_enabled = true++ SiteSetting.ai_bot_public_sharing_allowed_groups = ""+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"++ group = Fabricate(:group)+ SiteSetting.ai_bot_public_sharing_allowed_groups = group.id.to_s+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)++ group.add(owner)+ get "#{base_path}/#{key}"+ expect(response.status).to eq(200)++ group.remove(owner)+ get "#{base_path}/#{key}"+ expect(response.status).to eq(404)++ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"+ get "#{base_path}/#{key}"+ expect(response.status).to eq(200)++ # Shutting the gate must not affect the artifact route users reach through the post+ sign_in(owner)+ get "/discourse-ai/ai-bot/artifacts/#{artifact.id}"+ expect(response.status).to eq(200)+ end++ it "keeps unavailable snapshots listed for revocation without offering a working link" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]++ get "#{base_path}.json"+ expect(response.parsed_body["items"].first["available"]).to eq(true)++ source_post.trash!+ get "#{base_path}.json"+ expect(response.parsed_body["items"].first["available"]).to eq(false)++ source_post.recover!+ get "#{base_path}.json"+ expect(response.parsed_body["items"].first["available"]).to eq(true)++ SiteSetting.ai_bot_public_sharing_allowed_groups = "1"+ get "#{base_path}.json"+ expect(response.parsed_body["items"].first["available"]).to eq(false)+ expect(response.parsed_body["items"].first["share_key"]).to eq(key)++ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(204)+ get "#{base_path}.json"+ expect(response.parsed_body["items"]).to eq([])+ end++ it "lists an orphaned snapshot as unavailable until its owner revokes it" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ AiArtifact.where(id: artifact.id).delete_all++ get "#{base_path}.json", params: { type: "standalone" }+ expect(response.status).to eq(200)+ expect(+ response.parsed_body["items"].map { |item| [item["share_key"], item["available"]] },+ ).to eq([[key, false]])++ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(204)+ expect(AiArtifactShare.where(share_key: key)).not_to exist+ end++ it "merges shares and conversation events chronologically with type filters and stable card IDs" do+ second_artifact = Fabricate(:ai_artifact, post: source_post, user: owner, name: "Second")+ source_post.update_columns(+ cooked:+ "<div data-ai-artifact-id='#{artifact.id}'></div>" \+ "<div data-ai-artifact-id='#{second_artifact.id}'></div>",+ )+ conversation = SharedAiConversation.share_conversation(owner, topic)+ first_share = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ first_share.pin!(version_number: 0)+ second_share = AiArtifactShare.new(ai_artifact: second_artifact, user: owner)+ second_share.pin!(version_number: 0)+ timestamp = Time.utc(2025, 1, 1, 12, 0, 0, 123_456)+ [conversation, first_share, second_share].each do |record|+ record.update_column(:created_at, timestamp)+ end+ sign_in(owner)++ ordered_events = [+ [conversation.id, "conversation"],+ [first_share.id, "standalone"],+ [second_share.id, "standalone"],+ ].sort+ card_ids =+ lambda do |events|+ events.flat_map do |id, type|+ if type == "conversation"+ ["conversation-#{id}-#{artifact.id}", "conversation-#{id}-#{second_artifact.id}"]+ else+ ["standalone-#{id}"]+ end+ end+ end+ get "#{base_path}.json"+ expect(response.parsed_body["items"].map { |item| item["id"] }).to eq(+ card_ids.call(ordered_events.reverse),+ )+ expect(response.parsed_body["has_more"]).to eq(false)+ get "#{base_path}.json", params: { order: "oldest" }+ expect(response.parsed_body["items"].map { |item| item["id"] }).to eq(+ card_ids.call(ordered_events),+ )+ expect(response.parsed_body["items"].map { |item| item["type"] }.tally).to eq(+ "standalone" => 2,+ "conversation" => 2,+ )+ get "#{base_path}.json", params: { type: "standalone" }+ expect(response.parsed_body["items"].map { |item| item["share_key"] }).to contain_exactly(+ first_share.share_key,+ second_share.share_key,+ )+ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].map { |item| item["id"] }).to eq(+ [+ "conversation-#{conversation.id}-#{artifact.id}",+ "conversation-#{conversation.id}-#{second_artifact.id}",+ ],+ )+ end++ it "continues across tied timestamps and deleted records without skipping a conversation event" do+ source_post.update_columns(cooked: "<div data-ai-artifact-id='#{artifact.id}'></div>")+ conversation = SharedAiConversation.share_conversation(owner, topic)+ shares =+ 20.times.map do |index|+ extra = Fabricate(:ai_artifact, post: source_post, user: owner, name: "Extra #{index}")+ AiArtifactShare+ .new(ai_artifact: extra, user: owner)+ .tap { |share| share.pin!(version_number: 0) }+ end+ timestamp = Time.utc(2025, 1, 1, 12, 0, 0, 654_321)+ (shares + [conversation]).each { |record| record.update_column(:created_at, timestamp) }+ sign_in(owner)++ get "#{base_path}.json"+ first_page = response.parsed_body+ expect(first_page["items"].length).to eq(20)+ expect(first_page["has_more"]).to eq(true)+ seen_ids = first_page["items"].map { |item| item["id"] }+ share_to_delete = shares.find { |share| seen_ids.include?("standalone-#{share.id}") }+ share_to_delete.destroy!++ get "#{base_path}.json", params: { cursor: first_page["next_cursor"].to_json }+ remaining_ids = response.parsed_body["items"].map { |item| item["id"] }+ expect((seen_ids + remaining_ids).sort).to eq(+ (+ shares.map { |share| "standalone-#{share.id}" } ++ ["conversation-#{conversation.id}-#{artifact.id}"]+ ).sort,+ )+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ it "rejects invalid feed filters, orders, and cursors" do+ sign_in(owner)+ ["bad", "", "conversations"].each do |type|+ get "#{base_path}.json", params: { type: type }+ expect(response.status).to eq(400)+ end+ get "#{base_path}.json", params: { order: "random" }+ expect(response.status).to eq(400)+ [+ "oops",+ "[]",+ "{}",+ { id: 2 },+ { created_at: "yesterday", id: 1, type: "standalone", order: "newest", filter: "all" },+ ].each do |cursor|+ get "#{base_path}.json",+ params: {+ cursor: cursor.is_a?(Hash) && cursor.key?(:created_at) ? cursor.to_json : cursor,+ }+ expect(response.status).to eq(400)+ end+ AiArtifactShare.new(ai_artifact: artifact, user: owner).pin!(version_number: 0)+ get "#{base_path}.json"+ cursor =+ response.parsed_body["next_cursor"] ||+ {+ created_at: AiArtifactShare.last.created_at.utc.iso8601(6),+ id: AiArtifactShare.last.id,+ type: "standalone",+ order: "newest",+ filter: "all",+ }+ get "#{base_path}.json", params: { type: "conversation", cursor: cursor.to_json }+ expect(response.status).to eq(400)+ get "#{base_path}.json", params: { order: "oldest", cursor: cursor.to_json }+ expect(response.status).to eq(400)+ end++ it "does not split a conversation with more than twenty artifact cards" do+ artifacts = [artifact]+ 20.times do |index|+ artifacts << Fabricate(:ai_artifact, post: source_post, user: owner, name: "Card #{index}")+ end+ source_post.update_columns(+ cooked: artifacts.map { |item| "<div data-ai-artifact-id='#{item.id}'></div>" }.join,+ )+ SharedAiConversation.share_conversation(owner, topic)+ sign_in(owner)++ get "#{base_path}.json", params: { type: "conversation" }+ expect(response.parsed_body["items"].map { |item| item["name"] }).to eq(artifacts.map(&:name))+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ it "limits updates as well as creates" do+ RateLimiter.enable+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ 9.times { put "#{base_path}/#{key}.json", params: { version: 0 } }+ expect(response.status).to eq(200)+ put "#{base_path}/#{key}.json", params: { version: 0 }+ expect(response.status).to eq(429)+ ensure+ RateLimiter.disable+ end++ it "requires login for listing and refuses a guest attempting mutation" do+ get "#{base_path}.json"+ expect(response.status).not_to eq(200)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ expect(response.status).not_to eq(201)+ end++ it "runs the pinned forum snapshot with viewer identity and share-only storage" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ pinned_html = artifact.html+ artifact.update!(html: "<p>Future private version</p>")+ original =+ Fabricate(+ :ai_artifact_key_value,+ ai_artifact: artifact,+ user: owner,+ key: "source",+ value: "secret",+ public: true,+ )++ get "#{base_path}/#{key}/forum"+ expect(response.status).to eq(200)+ expect(response.headers["X-Frame-Options"]).to eq("SAMEORIGIN")+ expect(response.headers["Content-Security-Policy"]).to include("frame-ancestors 'self'")+ expect(response.headers["Cache-Control"]).to eq("no-store")+ frame = Nokogiri.HTML5(response.body).at_css("iframe")+ expect(frame["sandbox"]).to eq("allow-scripts allow-forms")+ expect(frame["srcdoc"]).to include(pinned_html, "\"user_id\":#{owner.id}")+ expect(frame["srcdoc"]).not_to include(artifact.html, original.value)+ expect(response.body).to include("artifact-share-key-values/#{key}.json", "csrf-token")+ expect(response.body).not_to include("artifact-key-values/#{artifact.id}.json")++ get "#{base_path}/#{key}"+ expect(response.body).not_to include(+ "csrf-token",+ "discourse-artifact-kv",+ "_discourse_user_data",+ )+ end++ it "runs native shares for guests without exposing identity or accepting writes" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ share.pin!(version_number: 0)+ storage = "/discourse-ai/ai-bot/artifact-share-key-values/#{share.share_key}.json"++ get "#{base_path}/#{share.share_key}/forum"+ expect(response.status).to eq(200)+ expect(Nokogiri.HTML5(response.body).at_css("iframe")["srcdoc"]).to include("\"user_id\":null")+ get storage, params: { all_users: true }+ expect(response.status).to eq(200)+ post storage, params: { key: "guest", value: "no" }+ expect(response.status).not_to eq(200)+ end++ it "isolates share keys and users, permits only public cross-user reads and own writes" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ storage = "/discourse-ai/ai-bot/artifact-share-key-values/#{key}.json"+ original =+ Fabricate(+ :ai_artifact_key_value,+ ai_artifact: artifact,+ user: owner,+ key: "source",+ value: "secret",+ public: true,+ )+ post storage, params: { key: "vote", value: "owner vote", public: true }+ expect(response.status).to eq(200)+ expect(original.reload.value).to eq("secret")++ other_user = Fabricate(:user)+ sign_in(other_user)+ get storage, params: { all_users: true }+ expect(response.parsed_body["key_values"].map { |item| item["key"] }).to eq(["vote"])+ expect(response.body).not_to include(original.value)+ post storage, params: { key: "vote", value: "other vote", public: false }+ expect(response.status).to eq(200)+ get storage+ expect(response.parsed_body["key_values"].map { |item| item["value"] }).to eq(["other vote"])+ delete storage, params: { key: "vote" }+ expect(response.status).to eq(200)+ get storage, params: { all_users: true }+ expect(response.parsed_body["key_values"].map { |item| item["value"] }).to eq(["owner vote"])+ end++ it "checks settings, owner eligibility, source trash, and revocation for the forum runtime and storage" do+ sign_in(owner)+ post "#{base_path}/#{artifact.id}.json", params: { version: 0 }+ key = response.parsed_body["share_key"]+ forum = "#{base_path}/#{key}/forum"+ storage = "/discourse-ai/ai-bot/artifact-share-key-values/#{key}.json"+ post storage, params: { key: "vote", value: "stored" }+ expect(response.status).to eq(200)++ SiteSetting.ai_bot_public_sharing_allowed_groups = "1"+ get forum+ expect(response.status).to eq(404)+ get storage+ expect(response.status).to eq(404)+ post storage, params: { key: "vote", value: "changed" }+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_public_sharing_allowed_groups = "10"+ source_post.trash!+ get forum+ expect(response.status).to eq(404)+ get storage+ expect(response.status).to eq(404)+ source_post.recover!+ topic.trash!+ get forum+ expect(response.status).to eq(404)+ get storage+ expect(response.status).to eq(404)+ topic.recover!+ SiteSetting.ai_bot_enabled = false+ get forum+ expect(response.status).to eq(404)+ get storage+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_enabled = true+ SiteSetting.ai_artifact_security = "disabled"+ get forum+ expect(response.status).to eq(404)+ get storage+ expect(response.status).to eq(404)+ SiteSetting.ai_artifact_security = "strict"+ delete "#{base_path}/#{key}.json"+ expect(response.status).to eq(204)+ get forum+ expect(response.status).to eq(404)+ get storage+ expect(response.status).to eq(404)+ end++ it "keeps other shares private even for admins and never borrows source keys" do+ first_share = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ first_share.pin!(version_number: 0)+ second_artifact = Fabricate(:ai_artifact, post: source_post, user: owner)+ second_share = AiArtifactShare.new(ai_artifact: second_artifact, user: owner)+ second_share.pin!(version_number: 0)+ first_share.key_values.create!(user: owner, key: "poll", value: "private vote")+ second_share.key_values.create!(user: owner, key: "poll", value: "other poll", public: true)+ Fabricate(+ :ai_artifact_key_value,+ ai_artifact: artifact,+ user: owner,+ key: "poll",+ value: "source vote",+ public: true,+ )+ sign_in(Fabricate(:admin))++ get "/discourse-ai/ai-bot/artifact-share-key-values/#{first_share.share_key}.json",+ params: {+ all_users: true,+ }+ expect(response.status).to eq(200)+ expect(response.parsed_body["key_values"]).to eq([])+ get "/discourse-ai/ai-bot/artifact-share-key-values/#{second_share.share_key}.json",+ params: {+ all_users: true,+ }+ expect(response.parsed_body["key_values"].map { |item| item["value"] }).to eq(["other poll"])+ end++ it "preserves the global login wall for native embeds and share storage" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ share.pin!(version_number: 0)+ SiteSetting.login_required = true++ get "#{base_path}/#{share.share_key}/forum"+ expect(response).to redirect_to("/login")+ get "/discourse-ai/ai-bot/artifact-share-key-values/#{share.share_key}.json"+ expect(response.status).to eq(403)+ end++ it "applies artifact storage key and value limits independently to each share" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: owner)+ share.pin!(version_number: 0)+ SiteSetting.ai_artifact_max_keys_per_user_per_artifact = 1+ SiteSetting.ai_artifact_kv_value_max_length = 5+ sign_in(owner)+ storage = "/discourse-ai/ai-bot/artifact-share-key-values/#{share.share_key}.json"++ post storage, params: { key: "one", value: "ok" }+ expect(response.status).to eq(200)+ post storage, params: { key: "two", value: "ok" }+ expect(response.status).to eq(422)+ post storage, params: { key: "one", value: "too long" }+ expect(response.status).to eq(422)+ get storage+ expect(response.parsed_body["key_values"].map { |item| item["value"] }).to eq(["ok"])+ end+enddiff --git a/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rbindex 14df0c11dfa..b669059b867 100644--- a/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb@@ -27,6 +27,245 @@ RSpec.describe DiscourseAi::AiBot::ArtifactsController doSiteSetting.ai_artifact_security = "strict"end+ describe "#embed" do+ it "renders current and explicit versions without an authenticated bridge even for a signed-in owner" do+ artifact.update!(metadata: { public: true })+ public_topic = Fabricate(:topic, user: user)+ public_post = Fabricate(:post, user: user, topic: public_topic)+ artifact.update!(post: public_post)+ version = artifact.create_new_version(html: "<p>Old public version</p>")+ artifact.update!(html: "<p>Current public version</p>")+ sign_in(user)++ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(200)+ expect(parse_srcdoc(response.body)).to include(artifact.html)+ expect(response.headers["X-Frame-Options"]).to be_nil+ expect(response.headers["Referrer-Policy"]).to eq("no-referrer")+ expect(response.headers["Cache-Control"]).to eq("no-store")+ expect(response.headers["X-Robots-Tag"]).to eq("noindex")+ expect(response.body).not_to include(+ "csrf-token",+ "discourse-artifact-kv",+ "_discourse_user_data",+ )+ expect(Nokogiri.HTML5(response.body).css("body > script")).to be_empty++ get AiArtifact.embed_url(artifact.id, version.version_number)+ expect(response.status).to eq(200)+ expect(parse_srcdoc(response.body)).to include(version.html)+ expect(parse_srcdoc(response.body)).not_to include(artifact.html)+ expect(AiArtifactShare.where(ai_artifact: artifact)).not_to exist++ get artifact.url+ expect(response.status).to eq(200)+ expect(response.body).to include("_discourse_user_data", "discourse-artifact-kv")+ end++ it "rejects an owner's private source, unpublished PM, missing versions, and trashed sources" do+ sign_in(user)+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)++ artifact.update!(metadata: { public: true })+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)++ public_topic = Fabricate(:topic, user: user)+ public_post = Fabricate(:post, user: user, topic: public_topic)+ artifact.update!(post: public_post)+ get AiArtifact.embed_url(artifact.id, 999)+ expect(response.status).to eq(404)+ get "#{AiArtifact.embed_url(artifact.id).delete_suffix("/embed")}/1garbage/embed"+ expect(response.status).to eq(404)+ get AiArtifact.embed_url("9223372036854775808")+ expect(response.status).to eq(404)+ get AiArtifact.embed_url(artifact.id, "2147483648")+ expect(response.status).to eq(404)+ public_post.trash!+ get AiArtifact.embed_url(artifact.id)+ expect(response.status).to eq(404)+ end++ it "honors the global login wall for a public source" do+ public_topic = Fabricate(:topic, user: user)+ artifact.update!(post: Fabricate(:post, user: user, topic: public_topic))+ SiteSetting.login_required = true++ get AiArtifact.embed_url(artifact.id)+ expect(response).to redirect_to("/login")+ end+ end++ describe "#shared" do+ it "renders only the shared artifact without the authenticated bridge" do+ SiteSetting.ai_bot_enabled = true+ group = Fabricate(:group)+ group.add(user)+ SiteSetting.ai_bot_public_sharing_allowed_groups = group.id.to_s+ artifact.update!(name: "<script>Untrusted title</script>")+ share = AiArtifactShare.new(ai_artifact: artifact, user: user)+ share.assign_attributes(share.snapshot_attributes(version_number: 0))+ share.save!++ get share.url++ expect(response.status).to eq(200)+ document = Nokogiri.HTML5(response.body)+ expect(document.css("body > *").map(&:name)).to eq(["iframe"])+ frame = document.at_css("body > iframe")+ expect(frame["title"]).to eq(artifact.name)+ expect(frame["sandbox"]).to eq("allow-scripts allow-forms")+ expect(frame["srcdoc"]).to include(artifact.html)+ expect(document.at_css("title").text).to eq(artifact.name)+ expect(document.css("body > script")).to be_empty+ expect(response.body).not_to include("csrf-token", "discourse-artifact-kv")+ end+ end++ describe "#shared_metadata" do+ fab!(:group)++ before do+ SiteSetting.ai_bot_enabled = true+ group.add(user)+ SiteSetting.ai_bot_public_sharing_allowed_groups = group.id.to_s+ end++ it "returns only the pinned snapshot name without exposing the source" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: user)+ share.assign_attributes(share.snapshot_attributes(version_number: 0))+ share.save!+ artifact.update!(name: "Changed private source", html: "<p>New private source</p>")+ artifact.create_new_version(html: "<p>Private future version</p>")++ get "/discourse-ai/ai-bot/artifact-shares/#{share.share_key}/metadata.json"++ expect(response.status).to eq(200)+ expect(response.media_type).to eq("application/json")+ expect(response.parsed_body).to eq({ "name" => share.name })+ expect(response.headers["Cache-Control"]).to eq("no-store")+ expect(response.headers["X-Robots-Tag"]).to eq("noindex")+ end++ it "hides missing shares and shares after group, source, or site access is lost" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: user)+ share.assign_attributes(share.snapshot_attributes(version_number: 0))+ share.save!+ path = "/discourse-ai/ai-bot/artifact-shares/#{share.share_key}/metadata.json"++ get "/discourse-ai/ai-bot/artifact-shares/unknown/metadata.json"+ expect(response.status).to eq(404)+ get path+ expect(response.parsed_body).to eq({ "name" => share.name })++ group.remove(user)+ get path+ expect(response.status).to eq(404)+ group.add(user)+ post.trash!+ get path+ expect(response.status).to eq(404)+ post.recover!+ SiteSetting.ai_bot_enabled = false+ get path+ expect(response.status).to eq(404)+ SiteSetting.ai_bot_enabled = true+ SiteSetting.ai_artifact_security = "disabled"+ get path+ expect(response.status).to eq(404)+ end++ it "keeps the global login wall for an anonymous metadata request" do+ share = AiArtifactShare.new(ai_artifact: artifact, user: user)+ share.assign_attributes(share.snapshot_attributes(version_number: 0))+ share.save!+ SiteSetting.login_required = true++ get "/discourse-ai/ai-bot/artifact-shares/#{share.share_key}/metadata.json"++ expect(response.status).to eq(403)+ expect(response.parsed_body["error_type"]).to eq("not_logged_in")+ end+ end++ describe "#metadata" do+ it "returns only the source name for base and existing versions to a permitted viewer" do+ version = artifact.create_new_version(html: "<p>Secret version</p>")+ sign_in(user)+ path = "/discourse-ai/ai-bot/artifacts/#{artifact.id}/metadata.json"++ get path+ expect(response.status).to eq(200)+ expect(response.media_type).to eq("application/json")+ expect(response.parsed_body).to eq({ "name" => artifact.name })+ expect(response.headers["Cache-Control"]).to eq("no-store")+ expect(response.headers["X-Robots-Tag"]).to eq("noindex")++ ["0", version.version_number.to_s].each do |requested_version|+ get path, params: { version: requested_version }+ expect(response.status).to eq(200)+ expect(response.parsed_body).to eq({ "name" => artifact.name })+ end+ end++ it "returns a public source name to guests and hides a trashed source" do+ artifact.update!(metadata: { public: true })+ path = "/discourse-ai/ai-bot/artifacts/#{artifact.id}/metadata.json"++ get path+ expect(response.status).to eq(200)+ expect(response.parsed_body).to eq({ "name" => artifact.name })++ topic.trash!+ get path+ expect(response.status).to eq(404)+ end++ it "rejects inaccessible sources, invalid IDs, and invalid or missing versions" do+ path = "/discourse-ai/ai-bot/artifacts/#{artifact.id}/metadata.json"+ get path+ expect(response.status).to eq(404)++ sign_in(user)+ %w[0 1garbage 999999999999999999999999999999999999999999].each do |bad_id|+ get "/discourse-ai/ai-bot/artifacts/#{bad_id}/metadata.json"+ expect(response.status).to eq(404)+ end+ [+ "1garbage",+ "-1",+ "01",+ "",+ "999",+ "999999999999999999999999999999999999999999",+ ].each do |bad_version|+ get path, params: { version: bad_version }+ expect(response.status).to eq(404)+ end+ get path, params: { version: %w[0 1] }+ expect(response.status).to eq(404)++ topic.trash!+ get path+ expect(response.status).to eq(404)+ end++ it "honors site security and the global login wall" do+ artifact.update!(metadata: { public: true })+ path = "/discourse-ai/ai-bot/artifacts/#{artifact.id}/metadata.json"+ SiteSetting.ai_artifact_security = "disabled"+ get path+ expect(response.status).to eq(404)++ SiteSetting.ai_artifact_security = "strict"+ SiteSetting.login_required = true+ get path+ expect(response.status).to eq(403)+ expect(response.parsed_body["error_type"]).to eq("not_logged_in")+ end+ end+describe "#show" doit "returns 404 when discourse_ai is disabled" doSiteSetting.discourse_ai_enabled = false@@ -201,11 +440,14 @@ RSpec.describe DiscourseAi::AiBot::ArtifactsController doexpect(style_tag.text).to include("alert")end- it "removes security headers and disables crawling" do+ it "restricts authenticated runtime framing to the forum and disables crawling" dosign_in(user)get "/discourse-ai/ai-bot/artifacts/#{artifact.id}"- expect(response.headers["X-Frame-Options"]).to eq(nil)- expect(response.headers["Content-Security-Policy"]).to include("unsafe-inline")+ expect(response.headers["X-Frame-Options"]).to eq("SAMEORIGIN")+ expect(response.headers["Content-Security-Policy"]).to include(+ "unsafe-inline",+ "frame-ancestors 'self'",+ )expect(response.headers["X-Robots-Tag"]).to eq("noindex")enddiff --git a/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rbindex f069ad2d501..b54a75ae5c5 100644--- a/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb@@ -43,6 +43,207 @@ RSpec.describe DiscourseAi::AiBot::SharedAiConversationsController doI18n.t("discourse_ai.share_ai.errors.#{key}")end+ describe "GET index" do+ it "lists only the owner's conversations without requiring artifact cards or exposing context" do+ sign_in(user)+ conversation = shared_conversation+ other_conversation =+ SharedAiConversation.share_conversation(+ attacker,+ Fabricate(:private_message_topic, user: attacker, recipient: bot_user),+ )+ conversation.update_columns(+ excerpt: "Private excerpt",+ context: [{ id: user_pm_share.posts.first.id, cooked: "Private context" }],+ )++ get "#{path}.json"++ expect(response).to have_http_status(:ok)+ expect(response.parsed_body).to eq(+ "items" => [+ {+ "id" => conversation.id,+ "share_key" => conversation.share_key,+ "title" => conversation.title,+ "url" => conversation.url,+ "created_at" => conversation.created_at.as_json,+ "available" => true,+ },+ ],+ "has_more" => false,+ "next_cursor" => nil,+ )+ expect(response.body).not_to include(+ conversation.excerpt,+ conversation.context.first["cooked"],+ other_conversation.share_key,+ )+ end++ it "returns unavailable snapshots for deleted posts, deleted topics, and revoked sharing groups" do+ sign_in(user)+ conversation = shared_conversation+ post = user_pm_share.posts.first+ post.trash!+ get "#{path}.json"+ expect(response.parsed_body["items"].sole["available"]).to eq(false)++ post.recover!+ user_pm_share.trash!+ get "#{path}.json"+ expect(response.parsed_body["items"].sole["available"]).to eq(false)++ user_pm_share.recover!+ SiteSetting.ai_bot_enabled = false+ get "#{path}.json"+ expect(response.parsed_body["items"].sole["available"]).to eq(false)++ SiteSetting.ai_bot_enabled = true+ SiteSetting.ai_bot_public_sharing_allowed_groups = ""+ get "#{path}.json"+ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["items"].sole["available"]).to eq(false)+ delete "#{path}/#{conversation.share_key}.json"+ expect(response).to have_http_status(:ok)+ expect(SharedAiConversation.exists?(conversation.id)).to eq(false)+ end++ it "retains a snapshot when its source topic or context post no longer exists" do+ sign_in(user)+ conversation = shared_conversation+ Post.where(id: conversation.context.first["id"]).delete_all+ get "#{path}.json"+ expect(response.parsed_body["items"].sole.slice("id", "available")).to eq(+ "id" => conversation.id,+ "available" => false,+ )++ Topic.where(id: conversation.target_id).delete_all+ get "#{path}.json"+ expect(response.parsed_body["items"].sole.slice("id", "available")).to eq(+ "id" => conversation.id,+ "available" => false,+ )+ delete "#{path}/#{conversation.share_key}.json"+ expect(response).to have_http_status(:ok)+ end++ it "does not mark context posts from another topic available" do+ sign_in(user)+ conversation = shared_conversation+ other_post = Fabricate(:post, topic: user_pm, user: user)+ conversation.update_columns(context: [{ id: other_post.id, cooked: other_post.cooked }])++ get "#{path}.json"++ expect(response.parsed_body["items"].sole["available"]).to eq(false)+ end++ it "paginates 20 rows in both directions without skipping tied timestamps or deleted rows" do+ sign_in(user)+ conversations =+ 22.times.map do |index|+ pm_topic = Fabricate(:private_message_topic, user: user, recipient: bot_user)+ post = Fabricate(:post, topic: pm_topic, user: user)+ SharedAiConversation.create!(+ user: user,+ target: pm_topic,+ title: "Conversation #{index}",+ llm_name: "Bot",+ excerpt: "Snapshot",+ context: [{ id: post.id, cooked: post.cooked }],+ )+ end+ timestamp = Time.utc(2026, 1, 1, 12, 0, 0, 123_456)+ SharedAiConversation.where(id: conversations.map(&:id)).update_all(created_at: timestamp)++ %w[newest oldest].each do |order|+ get "#{path}.json", params: { order: order }+ first_page = response.parsed_body+ expect(first_page["items"].size).to eq(20)+ expect(first_page["has_more"]).to eq(true)+ expect(first_page["next_cursor"].keys.sort).to eq(%w[created_at id order])+ expected_ids = first_page["items"].map { |item| item["id"] }+ remaining_ids =+ SharedAiConversation.where(user: user).where.not(id: expected_ids).pluck(:id)+ SharedAiConversation.find(expected_ids.last).destroy!+ get "#{path}.json", params: { order: order, cursor: first_page["next_cursor"].to_json }+ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["items"].map { |item| item["id"] }).to eq(+ order == "newest" ? remaining_ids.sort.reverse : remaining_ids.sort,+ )+ expect(response.parsed_body["has_more"]).to eq(false)+ expect(response.parsed_body["next_cursor"]).to be_nil+ end+ end++ it "rejects malformed, oversized, and order-mismatched cursors and invalid orders" do+ sign_in(user)+ get "#{path}.json", params: { order: "reverse" }+ expect(response).not_to have_http_status(:success)++ [+ "no json",+ "x" * 513,+ { order: "oldest", created_at: Time.now.utc.iso8601(6), id: 1 }.to_json,+ { order: "newest", created_at: "tomorrow", id: 1 }.to_json,+ { order: "newest", created_at: Time.now.utc.iso8601(6), id: 0 }.to_json,+ ].each do |cursor|+ get "#{path}.json", params: { cursor: cursor }+ expect(response).not_to have_http_status(:success)+ end+ end++ it "bounds queries when listing many conversations" do+ sign_in(user)+ 21.times do+ pm_topic = Fabricate(:private_message_topic, user: user, recipient: bot_user)+ post = Fabricate(:post, topic: pm_topic, user: user)+ SharedAiConversation.create!(+ user: user,+ target: pm_topic,+ title: pm_topic.title,+ llm_name: "Bot",+ excerpt: "Snapshot",+ context: [{ id: post.id, cooked: post.cooked }],+ )+ end++ queries = track_sql_queries { get "#{path}.json" }+ expect(response.parsed_body["items"].size).to eq(20)+ expect(queries.size).to be <= 230+ end++ it "does not list another owner's snapshots, even for an admin" do+ shared_conversation+ sign_in(attacker)+ get "#{path}.json"+ expect(response.parsed_body["items"]).to eq([])++ sign_in(Fabricate(:admin))+ get "#{path}.json"+ expect(response.parsed_body["items"]).to eq([])+ end++ it "requires login" do+ conversation = shared_conversation+ get "#{path}.json"+ expect(response).not_to have_http_status(:success)+ expect(response.body).not_to include(conversation.share_key)+ end++ it "requires the AI plugin setting for listing and revoking" do+ sign_in(user)+ conversation = shared_conversation+ SiteSetting.discourse_ai_enabled = false+ get "#{path}.json"+ expect(response).to have_http_status(:not_found)+ delete "#{path}/#{conversation.share_key}.json"+ expect(response).to have_http_status(:not_found)+ end+ end+describe "POST create" docontext "when logged in" dobefore { sign_in(user) }diff --git a/plugins/discourse-ai/test/javascripts/acceptance/ai-artifact-cooked-share-runtime-test.js b/plugins/discourse-ai/test/javascripts/acceptance/ai-artifact-cooked-share-runtime-test.jsnew file mode 100644index 00000000000..c4ac6d0e892--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/acceptance/ai-artifact-cooked-share-runtime-test.js@@ -0,0 +1,42 @@+import { visit } from "@ember/test-helpers";+import { test } from "qunit";+import { cloneJSON } from "discourse/lib/object";+import topicFixtures from "discourse/tests/fixtures/topic";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("AI artifact | cooked shared snapshot", function (needs) {+ needs.user();+ needs.settings({+ discourse_ai_enabled: true,+ ai_bot_enabled: true,+ ai_artifact_security: "lax",+ });+ needs.pretender((server, helper) => {+ const topic = cloneJSON(topicFixtures["/t/280/1.json"]);+ topic.post_stream.posts[0].cooked =+ '<blockquote><div class="ai-artifact" data-ai-artifact-share-key="post-key" data-ai-artifact-id="12" data-ai-artifact-version="2" data-ai-artifact-height="640" data-trace="ok"></div></blockquote>';+ server.get("/t/280.json", () => helper.response(topic));+ });++ test("cooked post decoration mounts the native renderer with share key precedence", async function (assert) {+ await visit("/t/internationalization-localization/280");+ assert+ .dom("#post_1 blockquote .ai-artifact iframe")+ .hasAttribute(+ "src",+ "/discourse-ai/ai-bot/artifact-shares/post-key/forum",+ "quoted post uses the native snapshot rather than the artifact version"+ )+ .hasAttribute("data-trace", "ok", "unrelated metadata is preserved")+ .doesNotHaveAttribute(+ "data-ai-artifact-share-key",+ "share key is not generic metadata"+ );+ assert+ .dom("#post_1 .ai-artifact-share")+ .doesNotExist("no eligibility component is mounted");+ assert+ .dom("#post_1 .ai-artifact__wrapper")+ .hasAttribute("style", /height: 640px/);+ });+});diff --git a/plugins/discourse-ai/test/javascripts/acceptance/ai-artifact-shared-profile-test.js b/plugins/discourse-ai/test/javascripts/acceptance/ai-artifact-shared-profile-test.jsnew file mode 100644index 00000000000..43638b1bc15--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/acceptance/ai-artifact-shared-profile-test.js@@ -0,0 +1,460 @@+import { click, currentURL, visit } from "@ember/test-helpers";+import { test } from "qunit";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";+import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";+import {+ disableLoadMoreObserver,+ enableLoadMoreObserver,+} from "discourse/ui-kit/d-load-more";++acceptance("AI artifact - Shared artifacts profile", function (needs) {+ const previewRequests = [];+ let conversationDeletes = 0;+ let artifactRequests = 0;+ let conversationRequests = 0;+ needs.hooks.beforeEach(() => {+ artifactRequests = 0;+ conversationRequests = 0;+ });+ needs.user();+ needs.settings({+ discourse_ai_enabled: true,+ ai_artifact_security: "strict",+ });+ needs.pretender((server, helper) => {+ server.get("/discourse-ai/ai-bot/artifact-shares.json", () => {+ artifactRequests++;+ return helper.response({+ has_more: false,+ next_cursor: null,+ items: [+ {+ id: "standalone-secret",+ type: "standalone",+ name: "Hello World",+ url: "/discourse-ai/ai-bot/artifact-shares/secret",+ share_key: "secret",+ version: 3,+ available: true,+ created_at: "2026-09-21T12:00:00Z",+ },+ {+ id: "conversation-42",+ type: "conversation",+ name: "Fireworks animation",+ topic_id: 42,+ artifact_id: 321,+ artifact_version: null,+ share_key: "shared",+ url: "/discourse-ai/ai-bot/shared-ai-conversations/shared",+ embed_url: "/artifacts/321/embed",+ available: true,+ created_at: "2026-09-20T12:00:00Z",+ },+ ],+ });+ });+ server.get("/discourse-ai/ai-bot/shared-ai-conversations.json", () => {+ conversationRequests++;+ return helper.response({+ has_more: false,+ next_cursor: null,+ items: [+ {+ id: 42,+ share_key: "shared",+ title: "A shared conversation",+ url: "/discourse-ai/ai-bot/shared-ai-conversations/shared",+ created_at: "2026-09-20T12:00:00Z",+ available: true,+ },+ ],+ });+ });+ server.get(+ "/discourse-ai/ai-bot/shared-ai-conversations/preview/42.json",+ (request) => {+ previewRequests.push(request.url);+ return helper.response({});+ }+ );+ server.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/shared.json",+ () => {+ conversationDeletes++;+ return helper.response({});+ }+ );+ });++ test("self profile offers actions and confirms conversation revoke", async function (assert) {+ await visit("/u/eviltrout/activity");+ assert+ .dom(".user-nav__activity-shared-artifacts a")+ .hasText("Shared AI artifacts", "artifacts use the canonical name");+ assert+ .dom(".user-nav__activity-shared-conversations a")+ .hasText("Shared AI conversations", "conversations have their own tab");+ await click(".user-nav__activity-shared-artifacts a");+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-artifacts",+ "the profile route opens"+ );+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "both share types appear together");+ assert.dom(".shared-artifacts__card:first-child h3").hasText("Hello World");+ assert+ .dom(".shared-artifacts__card:last-child h3")+ .hasText("Fireworks animation");+ assert+ .dom(".shared-artifacts iframe")+ .doesNotExist("the profile does not load either artifact document");+ assert+ .dom(".shared-artifacts__card .shared-artifacts__actions button")+ .exists(+ { count: 8 },+ "both cards have copy link, both embeds and revoke"+ );+ assert+ .dom(".shared-artifacts__embed-post")+ .exists({ count: 2 }, "both post actions are direct buttons");+ assert+ .dom(".shared-artifacts__embed-website")+ .exists({ count: 2 }, "both website actions are direct buttons");+ assert+ .dom(".shared-artifacts__card:last-child .shared-artifacts__embed-post")+ .hasText("Embed in post");+ assert+ .dom(+ ".shared-artifacts__card:first-child .shared-artifacts__embed-website"+ )+ .hasText("Embed on website");+ assert+ .dom(".shared-artifacts__revoke.btn-danger")+ .exists({ count: 2 }, "both revoke buttons are red");+ assert+ .dom(".shared-artifacts__card:last-child .shared-artifacts__revoke")+ .hasText("Revoke conversation share");+ assert.deepEqual(previewRequests, [], "listing does not fetch previews");++ await click(".shared-artifacts__card:last-child .shared-artifacts__revoke");+ assert+ .dom("#dialog-title")+ .hasText("Revoke conversation share?", "the dialog identifies its scope");+ assert+ .dom(".dialog-body")+ .hasText(+ "This permanently stops the shared conversation and its artifact embeds. Standalone links are not revoked.",+ "the confirmation explains what is affected"+ );+ assert+ .dom(".dialog-footer .btn-danger")+ .hasText("Revoke conversation share", "the confirm action is dangerous");+ assert.strictEqual(+ conversationDeletes,+ 0,+ "no deletion before confirmation"+ );+ assert.dom(".shared-artifacts__card").exists({ count: 2 });++ await click(".dialog-footer .btn-default");+ assert.strictEqual(conversationDeletes, 0, "cancel sends no deletion");+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "cancel retains the feed");++ await click(".shared-artifacts__card:last-child .shared-artifacts__revoke");+ assert.strictEqual(+ conversationDeletes,+ 0,+ "reopening still does not delete"+ );+ await click(".dialog-footer .btn-danger");+ assert.strictEqual(+ conversationDeletes,+ 1,+ "confirmation sends one deletion"+ );+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 1 }, "confirmed conversation share is removed");+ assert.dom(".shared-artifacts__card h3").hasText("Hello World");+ assert+ .dom(".ai-share-full-topic-modal")+ .doesNotExist("no management modal is opened");+ assert.deepEqual(previewRequests, [], "revoke does not fetch previews");+ });++ test("legacy artifact URL redirects to canonical URL without an extra feed request", async function (assert) {+ await visit("/u/eviltrout/activity/shared-artifacts");+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-artifacts",+ "legacy link resolves to canonical route"+ );+ assert.strictEqual(artifactRequests, 1, "only canonical model is fetched");+ assert.strictEqual(+ conversationRequests,+ 0,+ "conversation feed is not fetched"+ );+ });++ test("conversations tab loads only the conversation feed", async function (assert) {+ await visit("/u/eviltrout/activity");+ await click(".user-nav__activity-shared-conversations a");+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-conversations",+ "canonical conversation route opens"+ );+ assert+ .dom("#shared-conversations-heading")+ .hasText("Shared AI conversations");+ assert+ .dom(".shared-conversations__card h3")+ .hasText("A shared conversation");+ assert.strictEqual(artifactRequests, 0, "artifact feed is not fetched");+ assert.strictEqual(+ conversationRequests,+ 1,+ "conversation feed is fetched once"+ );+ assert+ .dom(".shared-conversations iframe")+ .doesNotExist("no artifact embeds");+ assert.dom(".shared-conversations__actions button").exists({ count: 2 });+ assert.dom(".shared-conversations__embed-post").doesNotExist("no embeds");+ assert+ .dom(".shared-conversations__manage")+ .doesNotExist("no manage action");+ });++ test("other profiles do not show or open the private page", async function (assert) {+ await visit("/u/charlie/activity");+ assert+ .dom(".user-nav__activity-shared-artifacts")+ .doesNotExist("private artifact tab is hidden");+ assert+ .dom(".user-nav__activity-shared-conversations")+ .doesNotExist("private conversation tab is hidden");++ await visit("/u/charlie/activity/shared-ai-conversations");+ assert.notStrictEqual(+ currentURL(),+ "/u/charlie/activity/shared-ai-conversations",+ "direct conversation navigation is guarded"+ );+ assert.strictEqual(conversationRequests, 0, "no private feed request");++ await visit("/u/charlie/activity/shared-artifacts");+ assert.notStrictEqual(+ currentURL(),+ "/u/charlie/activity/shared-ai-artifacts",+ "legacy route does not bypass the guard"+ );+ await visit("/u/charlie/activity/shared-ai-artifacts");+ assert.notStrictEqual(+ currentURL(),+ "/u/charlie/activity/shared-ai-artifacts",+ "direct navigation redirects away from the private page"+ );+ });+});++acceptance("AI artifact - Shared artifacts scrolling", function (needs) {+ needs.user();+ needs.settings({+ discourse_ai_enabled: true,+ ai_artifact_security: "strict",+ });+ needs.pretender((server, helper) => {+ server.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ if (request.queryParams.cursor) {+ return helper.response({+ items: [+ {+ id: "conversation-43",+ type: "conversation",+ name: "Later conversation",+ url: "/conversation/43",+ embed_url: "/artifacts/345/1/embed",+ available: true,+ share_key: "share-43",+ topic_id: 43,+ artifact_id: 345,+ artifact_version: 1,+ },+ ],+ has_more: false,+ next_cursor: null,+ });+ }+ return helper.response({+ items: [+ {+ id: "standalone-first",+ type: "standalone",+ name: "First standalone",+ url: "/standalone/first",+ share_key: "first",+ available: true,+ },+ ],+ has_more: true,+ next_cursor: { after: ["2026-09-21", 1] },+ });+ });+ });++ test("scroll observer automatically appends the next mixed page", async function (assert) {+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ try {+ await visit("/u/eviltrout/activity/shared-ai-artifacts");+ assert.dom(".shared-artifacts__card").exists({ count: 1 });+ const sentinel = observations.find(({ element }) =>+ element.closest(".shared-artifacts")+ );+ assert.true(!!sentinel, "the list has a load-more observer");+ await sentinel.trigger();+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "the next page loads without a button");+ assert+ .dom(".shared-artifacts__card:last-child h3")+ .hasText("Later conversation");+ assert+ .dom(".shared-artifacts iframe")+ .doesNotExist("scrolling never mounts artifact documents");+ } finally {+ disableLoadMoreObserver();+ }+ });+});++acceptance("AI artifact - Shared AI artifacts disabled", function (needs) {+ let requests = 0;+ needs.hooks.beforeEach(() => {+ requests = 0;+ });+ needs.user();+ needs.settings({+ discourse_ai_enabled: true,+ ai_artifact_security: "disabled",+ });+ needs.pretender((server, helper) => {+ server.get("/discourse-ai/ai-bot/artifact-shares.json", () => {+ requests++;+ return helper.response({+ items: [+ {+ id: "conversation-42",+ type: "conversation",+ name: "Unavailable conversation",+ share_key: "shared",+ url: "/discourse-ai/ai-bot/shared-ai-conversations/shared",+ available: false,+ },+ ],+ has_more: false,+ next_cursor: null,+ });+ });+ server.get("/discourse-ai/ai-bot/shared-ai-conversations.json", () =>+ helper.response({ items: [], has_more: false, next_cursor: null })+ );+ });++ test("owner can open disabled-security management from the tab and direct or legacy URLs", async function (assert) {+ await visit("/u/eviltrout/activity");+ assert+ .dom(".user-nav__activity-shared-artifacts a")+ .exists("management tab is visible");+ await click(".user-nav__activity-shared-artifacts a");+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-artifacts"+ );+ assert+ .dom(".shared-artifacts__card a")+ .doesNotExist("unavailable item has no dead link");+ assert+ .dom(".shared-artifacts__unavailable")+ .exists("unavailable item is explained");+ assert+ .dom(".shared-artifacts__actions button")+ .exists({ count: 1 }, "only revoke remains");+ await visit("/u/eviltrout/activity/shared-artifacts");+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-artifacts",+ "legacy URL redirects"+ );+ assert.strictEqual(+ requests,+ 2,+ "each visit fetches only the management feed"+ );+ });++ test("disabled security does not expose another user's management routes", async function (assert) {+ await visit("/u/charlie/activity");+ assert+ .dom(".user-nav__activity-shared-artifacts")+ .doesNotExist("other user's tab stays hidden");+ for (const path of ["shared-ai-artifacts", "shared-artifacts"]) {+ await visit(`/u/charlie/activity/${path}`);+ assert.notStrictEqual(+ currentURL(),+ `/u/charlie/activity/shared-ai-artifacts`,+ "private route redirects"+ );+ }+ assert.strictEqual(requests, 0, "no private feed request");+ });+});++acceptance("AI sharing - plugin disabled", function (needs) {+ needs.user();+ needs.settings({ discourse_ai_enabled: false });++ test("neither activity tab nor route is available", async function (assert) {+ await visit("/u/eviltrout/activity");+ assert.dom(".user-nav__activity-shared-artifacts").doesNotExist();+ assert.dom(".user-nav__activity-shared-conversations").doesNotExist();+ await visit("/u/eviltrout/activity/shared-ai-conversations");+ assert.notStrictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-conversations",+ "conversation route is guarded"+ );+ });+});++acceptance("AI sharing - bot disabled", function (needs) {+ needs.user();+ needs.settings({+ discourse_ai_enabled: true,+ ai_bot_enabled: false,+ ai_artifact_security: "disabled",+ });+ needs.pretender((server, helper) => {+ server.get("/discourse-ai/ai-bot/shared-ai-conversations.json", () =>+ helper.response({ items: [], has_more: false, next_cursor: null })+ );+ });++ test("existing conversations can still be managed", async function (assert) {+ await visit("/u/eviltrout/activity/shared-ai-conversations");+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-conversations",+ "management route is not gated by bot sharing eligibility"+ );+ assert.dom(".shared-conversations__empty").exists();+ assert.dom(".user-nav__activity-shared-conversations").exists();+ });+});diff --git a/plugins/discourse-ai/test/javascripts/integration/ai-artifact-rich-editor-test.js b/plugins/discourse-ai/test/javascripts/integration/ai-artifact-rich-editor-test.jsnew file mode 100644index 00000000000..7f4a2e01e57--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/ai-artifact-rich-editor-test.js@@ -0,0 +1,579 @@+import {+ click,+ fillIn,+ settled,+ triggerKeyEvent,+ waitFor,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import {+ registerRichEditorExtension,+ resetRichEditorExtensions,+} from "discourse/lib/composer/rich-editor-extensions";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";+import { metaModifier } from "discourse/tests/helpers/qunit-helpers";+import {+ setupRichEditor,+ testMarkdown,+} from "discourse/tests/helpers/rich-editor-helper";+import richEditorExtension from "discourse/plugins/discourse-ai/discourse/lib/ai-artifact-rich-editor-extension";++module(+ "Integration | Component | prosemirror-editor - AI artifact extension",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(async function () {+ this.siteSettings.discourse_ai_enabled = true;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/:share_key/metadata.json",+ () => response(404, {})+ );+ pretender.get("/discourse-ai/ai-bot/artifacts/:id/metadata.json", () =>+ response(404, {})+ );+ await resetRichEditorExtensions();+ registerRichEditorExtension(richEditorExtension);+ });++ test("shows configured embed options on the card", async function (assert) {+ await setupRichEditor(+ assert,+ '[ai-artifact share="shared" autorun="true" height="2000" seamless="true"]'+ );++ assert+ .dom(".composer-ai-artifact__kind")+ .doesNotExist("omits the redundant artifact kind subtitle");+ assert+ .dom('.composer-ai-artifact__options [data-option="autorun"]')+ .hasText(+ "Run automatically: On",+ "shows the configured autorun preference"+ );+ assert+ .dom('.composer-ai-artifact__options [data-option="height"]')+ .hasText("Height: 2000 px", "shows the configured height");+ assert+ .dom('.composer-ai-artifact__options [data-option="seamless"]')+ .hasText("Seamless: On", "shows the configured seamless preference");+ assert+ .dom(".ai-artifact-options-modal")+ .doesNotExist("does not open a dialog");+ assert+ .dom(".ProseMirror iframe")+ .doesNotExist("does not run the artifact");+ });++ test("distinguishes default and disabled options on the card", async function (assert) {+ await setupRichEditor(+ assert,+ '[ai-artifact share="shared" autorun="false"]'+ );++ assert+ .dom('.composer-ai-artifact__options [data-option="autorun"]')+ .hasText(+ "Run automatically: Off",+ "keeps explicit off distinct from default"+ );+ assert+ .dom('.composer-ai-artifact__options [data-option="height"]')+ .hasText("Height: Default", "shows the default height");+ assert+ .dom('.composer-ai-artifact__options [data-option="seamless"]')+ .hasText("Seamless: Default", "shows the default seamless preference");+ });++ for (const tag of [+ '[ai-artifact share="abc_123" autorun="true"]',+ '[ai-artifact share="abc_123" autorun="false"]',+ '[ai-artifact id="123" version="2" autorun="true"]',+ '[ai-artifact id="9999999999999999999" autorun="false"]',+ '[ai-artifact share="abc_123" height="2000" seamless="true"]',+ '[ai-artifact id="7" height="42" seamless="false"]',+ ]) {+ test(`round-trips ${tag} without running it`, async function (assert) {+ await testMarkdown(+ assert,+ tag,+ () => {+ assert+ .dom(".ProseMirror .composer-ai-artifact")+ .includesText("AI artifact");+ assert+ .dom(".ProseMirror .composer-ai-artifact")+ .doesNotIncludeText(tag);+ assert+ .dom(".composer-ai-artifact__edit")+ .exists("options are always reachable");+ assert.dom(".ProseMirror .ai-artifact").doesNotExist();+ assert.dom(".ProseMirror iframe").doesNotExist();+ },+ tag+ );+ });+ }++ test("preserves surrounding text and switches between editor modes", async function (assert) {+ const tag = '[ai-artifact id="7" version="3" autorun="false"]';+ const markdown = `Before\n\n${tag}\n\nAfter`;+ const [editor] = await setupRichEditor(assert, markdown, {+ multiToggle: true,+ });++ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.strictEqual(editor.value, markdown);++ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.strictEqual(editor.value, markdown);+ });++ test("preserves an artifact and following paragraph in one blockquote", async function (assert) {+ const markdown = '> [ai-artifact id="1"]\n>\n> after';+ const [editor] = await setupRichEditor(assert, markdown, {+ multiToggle: true,+ });++ assert+ .dom(".ProseMirror blockquote")+ .exists({ count: 1 }, "the artifact and paragraph share a blockquote");+ assert+ .dom(".ProseMirror blockquote .composer-ai-artifact")+ .exists("the artifact remains nested");+ assert+ .dom(".ProseMirror blockquote p")+ .hasText("after", "the following paragraph remains nested");+ assert.strictEqual(+ editor.value,+ markdown,+ "serialization keeps the quote open"+ );++ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert+ .dom(".ProseMirror blockquote")+ .exists({ count: 1 }, "reparsing keeps one blockquote");+ assert+ .dom(".ProseMirror blockquote .composer-ai-artifact")+ .exists("reparsing keeps the artifact nested");+ assert+ .dom(".ProseMirror blockquote p")+ .hasText("after", "reparsing keeps the paragraph nested");+ });++ test("preserves an artifact and following paragraph in one list item", async function (assert) {+ const markdown = '- [ai-artifact id="1"]\n\n after';+ const [editor] = await setupRichEditor(assert, markdown, {+ multiToggle: true,+ });++ assert+ .dom(".ProseMirror li")+ .exists({ count: 1 }, "the artifact and paragraph share a list item");+ assert+ .dom(".ProseMirror li .composer-ai-artifact")+ .exists("the artifact remains nested");+ assert+ .dom(".ProseMirror li p")+ .hasText("after", "the following paragraph remains nested");+ assert.strictEqual(+ editor.value,+ '* [ai-artifact id="1"]\n\n after',+ "serialization keeps the list open"+ );++ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert+ .dom(".ProseMirror li")+ .exists({ count: 1 }, "reparsing keeps one item");+ assert+ .dom(".ProseMirror li .composer-ai-artifact")+ .exists("reparsing keeps the artifact nested");+ assert+ .dom(".ProseMirror li p")+ .hasText("after", "reparsing keeps the paragraph nested");+ });++ test("does not add extra spacing between list items", async function (assert) {+ const markdown = '- [ai-artifact id="1"]\n- after';+ const [editor] = await setupRichEditor(assert, markdown, {+ multiToggle: true,+ });++ assert.dom(".ProseMirror li").exists({ count: 2 }, "both items render");+ assert+ .dom(".ProseMirror li:first-child .composer-ai-artifact")+ .exists("the artifact is in the first item");+ assert+ .dom(".ProseMirror li:last-child p")+ .hasText("after", "the next item is separate");+ assert.strictEqual(+ editor.value,+ '* [ai-artifact id="1"]\n\n* after',+ "serialization adds only one blank line between items"+ );++ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert.dom(".ProseMirror li").exists({ count: 2 }, "both items reparse");+ assert+ .dom(".ProseMirror li:first-child .composer-ai-artifact")+ .exists("the artifact stays in the first item");+ assert+ .dom(".ProseMirror li:last-child p")+ .hasText("after", "the second item stays separate");+ });++ test("keeps inline tags and code inert", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ 'Inline [ai-artifact id="7" height="2000" seamless="true"] text.\n\n`[ai-artifact id="7" height="2000"]`\n\n```\n[ai-artifact id="7" height="2000" seamless="true"]\n```'+ );+ assert.dom(".ProseMirror .composer-ai-artifact").doesNotExist();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(editor.value.includes('[ai-artifact id="7" height="2000"]'));+ });++ test("pastes cooked share and legacy layout attributes safely", async function (assert) {+ const [editor] = await setupRichEditor(assert, "Before");+ editor.view.pasteHTML(+ '<div class="ai-artifact" data-ai-artifact-id="7" data-ai-artifact-version="2" data-ai-artifact-autorun="true" data-ai-artifact-height="400" data-ai-artifact-width="600" data-ai-artifact-seamless="true"></div>'+ );+ await settled();++ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror .ai-artifact").doesNotExist();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(editor.value.includes('data-ai-artifact-height="400"'));+ assert.true(editor.value.includes('data-ai-artifact-width="600"'));+ assert.true(editor.value.includes('data-ai-artifact-seamless="true"'));+ assert.true(editor.value.includes('data-ai-artifact-autorun="true"'));+ assert.true(editor.value.includes("Before"));++ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert.true(editor.value.includes('data-ai-artifact-height="400"'));+ assert.true(editor.value.includes('data-ai-artifact-width="600"'));+ assert.true(editor.value.includes('data-ai-artifact-seamless="true"'));+ assert.dom(".ProseMirror iframe").doesNotExist();+ });++ test("reopens legacy artifact HTML as a card while leaving other HTML and code inert", async function (assert) {+ const legacy =+ '<div class="ai-artifact" data-ai-artifact-id="7" data-ai-artifact-version="2" data-ai-artifact-height="400" data-ai-artifact-width="600" data-ai-artifact-seamless="true"></div>';+ const [editor] = await setupRichEditor(+ assert,+ `${legacy}\n\n<div class="other">Hello</div>\n\n\`\`\`html\n${legacy}\n\`\`\``,+ { multiToggle: true }+ );+ assert+ .dom(".ProseMirror .composer-ai-artifact")+ .exists("legacy HTML is an artifact card");+ assert+ .dom(".ProseMirror .html-block")+ .exists({ count: 1 }, "unrelated HTML remains generic");+ assert+ .dom(".ProseMirror pre:not(.html-block) code")+ .exists("fenced HTML remains code");+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(+ editor.value.includes('data-ai-artifact-width="600"'),+ "legacy width is preserved"+ );+ assert.true(+ editor.value.includes('data-ai-artifact-height="400"'),+ "legacy height is preserved"+ );+ assert.true(+ editor.value.includes('data-ai-artifact-seamless="true"'),+ "legacy seamless is preserved"+ );+ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert+ .dom(".ProseMirror .composer-ai-artifact")+ .exists("reopening retains the artifact card");+ assert+ .dom(".ProseMirror .html-block")+ .exists({ count: 1 }, "only unrelated HTML remains generic");+ assert.dom(".ProseMirror iframe").doesNotExist();+ });++ test("keeps malformed layout tags and unrecognized HTML inert", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ '[ai-artifact id="7" height="2001"]\n\n[ai-artifact share="key" seamless="1"]\n\n<div class="ai-artifact" data-ai-artifact-id="7" onclick="alert(1)"></div>'+ );+ assert.dom(".ProseMirror .composer-ai-artifact").doesNotExist();+ assert+ .dom(".ProseMirror .html-block")+ .exists("unknown HTML stays generic");+ assert.dom(".ProseMirror iframe, .ProseMirror script").doesNotExist();+ assert.true(+ editor.value.includes('height="2001"'),+ "invalid tag is retained"+ );+ assert.true(+ editor.value.includes('seamless="1"'),+ "invalid boolean is retained"+ );+ });++ test("reopens encoded legacy attributes without double-escaping", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ '<div class="ai-artifact" data-ai-artifact-share-key="shared" data-ai-artifact-width="600&auto"></div>',+ { multiToggle: true }+ );+ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.strictEqual(+ editor.value,+ '<div class="ai-artifact" data-ai-artifact-share-key="shared" data-ai-artifact-width="600&auto"></div>',+ "the escaped legacy width is preserved"+ );+ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror iframe").doesNotExist();+ });++ test("pastes cooked share as a compact tag", async function (assert) {+ const [editor] = await setupRichEditor(assert, "");+ editor.view.pasteHTML(+ '<div class="ai-artifact" data-ai-artifact-share-key="shared" data-ai-artifact-autorun="false"></div>'+ );+ await settled();++ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(+ editor.value.includes('[ai-artifact share="shared" autorun="false"]')+ );+ });++ test("normalizes legacy autorun values without dropping the artifact", async function (assert) {+ const [editor] = await setupRichEditor(assert, "");+ editor.view.pasteHTML(+ '<div class="ai-artifact" data-ai-artifact-id="7" data-ai-artifact-autorun="1" data-ai-artifact-height="350"></div>'+ );+ await settled();++ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(editor.value.includes('autorun="true"'));+ assert.true(editor.value.includes('height="350"'));+ });++ test("pastes a standalone plain-text tag into an empty paragraph", async function (assert) {+ const [editor] = await setupRichEditor(assert, "");+ editor.view.pasteHTML('<p>[ai-artifact id="7" autorun="true"]</p>');+ await settled();++ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(editor.value.includes('[ai-artifact id="7" autorun="true"]'));+ });++ test("typing a standalone tag creates a safe artifact block", async function (assert) {+ const [editor] = await setupRichEditor(assert, "");+ const { view } = editor;+ view.dispatch(+ view.state.tr.insertText('[ai-artifact id="7" autorun="true"')+ );+ const pos = view.state.selection.from;+ view.someProp("handleTextInput", (handler) =>+ handler(view, pos, pos, "]")+ );+ await settled();++ assert.dom(".ProseMirror .composer-ai-artifact").exists();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.true(editor.value.includes('[ai-artifact id="7" autorun="true"]'));+ });+ test("uses only inert title metadata and never renders executable HTML", async function (assert) {+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/shared/metadata.json",+ () => response({ name: '<img src=x onerror="alert(1)"> My art' })+ );+ const [editor] = await setupRichEditor(+ assert,+ '[ai-artifact share="shared"]'+ );+ await waitFor(".composer-ai-artifact__title");+ await settled();++ assert+ .dom(".composer-ai-artifact__title")+ .hasText('<img src=x onerror="alert(1)"> My art');+ assert+ .dom(".ProseMirror img, .ProseMirror iframe, .ProseMirror script")+ .doesNotExist();+ assert.strictEqual(editor.value, '[ai-artifact share="shared"]');+ });++ test("edits source identity, version, autorun and height in one undoable change", async function (assert) {+ const original = '[ai-artifact id="7" version="3" autorun="false"]';+ const [editor] = await setupRichEditor(+ assert,+ '[ai-artifact id="7" version="3" autorun="false"]',+ { withMenus: true }+ );+ await click(".composer-ai-artifact__edit");+ assert.dom(".ai-artifact-options-modal").exists();+ await fillIn('[data-name="reference"] input', "12");+ await fillIn('[data-name="version"] input', "4");+ await formKit().field("autorun").select("true");+ await fillIn('[data-name="height"] input', "2000");+ await formKit().field("seamless").select("true");+ await click(".ai-artifact-options-modal__apply");++ assert.dom(".ai-artifact-options-modal").doesNotExist();+ assert.strictEqual(+ editor.value,+ '[ai-artifact id="12" version="4" autorun="true" height="2000" seamless="true"]',+ "layout edits serialize as a compact tag"+ );+ assert+ .dom('.composer-ai-artifact__options [data-option="height"]')+ .hasText("Height: 2000 px", "refreshes the static summary after Apply");+ assert.dom(".ProseMirror .html-block").doesNotExist();+ assert.dom(".ProseMirror iframe").doesNotExist();+ assert.dom(".ProseMirror").isFocused("focus returns to the editor");++ await triggerKeyEvent(".ProseMirror", "keydown", "Z", metaModifier);+ assert.strictEqual(editor.value, original, "one undo reverts the edit");+ await triggerKeyEvent(".ProseMirror", "keydown", "Z", {+ ...metaModifier,+ shiftKey: true,+ });+ assert.strictEqual(+ editor.value,+ '[ai-artifact id="12" version="4" autorun="true" height="2000" seamless="true"]',+ "redo restores the compact edit"+ );+ await click(".composer-toggle-switch");+ await click(".composer-toggle-switch");+ assert+ .dom(".ProseMirror .composer-ai-artifact")+ .exists("the reopened tag is a card");+ assert+ .dom(".ProseMirror .html-block, .ProseMirror iframe")+ .doesNotExist();+ });++ test("keeps share identity, stored preference, and legacy width on no-op edit", async function (assert) {+ this.siteSettings.ai_artifact_security = "strict";+ const [editor] = await setupRichEditor(assert, "", { withMenus: true });+ editor.view.pasteHTML(+ '<div class="ai-artifact" data-ai-artifact-share-key="shared" data-ai-artifact-autorun="true" data-ai-artifact-width="600"></div>'+ );+ await settled();+ const original = editor.value;+ await click(".composer-ai-artifact__edit");+ assert+ .dom('[data-name="version"]')+ .doesNotExist("a share has no source version");+ assert+ .dom(".ai-artifact-options-modal__policy")+ .includesText("requires a click");+ await click(".ai-artifact-options-modal__apply");+ assert.strictEqual(editor.value, original);+ assert.true(editor.value.includes('data-ai-artifact-width="600"'));+ assert.true(editor.value.includes('data-ai-artifact-autorun="true"'));+ });++ test("keeps long source IDs and legacy layout on unrelated changes", async function (assert) {+ const [editor] = await setupRichEditor(assert, "", { withMenus: true });+ editor.view.pasteHTML(+ '<div class="ai-artifact" data-ai-artifact-id="9999999999999999999" data-ai-artifact-version="1234567890123456789" data-ai-artifact-height="2600" data-ai-artifact-width="640" data-ai-artifact-seamless="1"></div>'+ );+ await settled();+ await click(".composer-ai-artifact__edit");+ await formKit().field("autorun").select("false");+ await click(".ai-artifact-options-modal__apply");+ assert.true(+ editor.value.includes('data-ai-artifact-id="9999999999999999999"')+ );+ assert.true(+ editor.value.includes('data-ai-artifact-version="1234567890123456789"')+ );+ assert.true(editor.value.includes('data-ai-artifact-height="2600"'));+ assert.true(editor.value.includes('data-ai-artifact-width="640"'));+ assert.true(editor.value.includes('data-ai-artifact-seamless="1"'));+ });++ test("accepts this site's copied share link but rejects an external link", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ '[ai-artifact share="shared"]',+ { withMenus: true }+ );+ await click(".composer-ai-artifact__edit");+ await fillIn(+ '[data-name="reference"] input',+ `${window.location.origin}/discourse-ai/ai-bot/artifact-shares/another`+ );+ await click(".ai-artifact-options-modal__apply");+ assert.strictEqual(editor.value, '[ai-artifact share="another"]');++ await click(".composer-ai-artifact__edit");+ await fillIn(+ '[data-name="reference"] input',+ "https://example.org/discourse-ai/ai-bot/artifact-shares/other"+ );+ await click(".ai-artifact-options-modal__apply");+ assert+ .dom(".ai-artifact-options-modal")+ .exists("external URLs are rejected");+ assert.strictEqual(editor.value, '[ai-artifact share="another"]');+ });++ test("keeps the absent autorun preference distinct from explicit off", async function (assert) {+ const [editor] = await setupRichEditor(assert, '[ai-artifact id="7"]', {+ withMenus: true,+ });+ await click(".composer-ai-artifact__edit");+ assert.dom('[data-name="reference"]').doesNotIncludeText("optional");+ assert.dom('[data-name="autorun"] select').hasValue("default");+ assert.dom('[data-name="seamless"] select').hasValue("default");+ await formKit().field("autorun").select("false");+ await click(".ai-artifact-options-modal__apply");+ assert.strictEqual(editor.value, '[ai-artifact id="7" autorun="false"]');++ await click(".composer-ai-artifact__edit");+ await formKit().field("autorun").select("default");+ await click(".ai-artifact-options-modal__apply");+ assert.strictEqual(editor.value, '[ai-artifact id="7"]');+ });++ test("cancel and invalid references leave the original embed untouched", async function (assert) {+ const [editor] = await setupRichEditor(assert, '[ai-artifact id="7"]', {+ withMenus: true,+ });+ const original = editor.value;+ await click(".composer-ai-artifact__edit");+ await fillIn('[data-name="reference"] input', "other");+ await click(".ai-artifact-options-modal__cancel");+ assert.strictEqual(editor.value, original);+ assert.dom(".ProseMirror").isFocused("cancel returns focus");++ await click(".composer-ai-artifact__edit");+ await fillIn('[data-name="reference"] input', 'bad ref"<');+ await fillIn('[data-name="height"] input', "-1");+ await click(".ai-artifact-options-modal__apply");+ assert+ .dom(".ai-artifact-options-modal")+ .exists("invalid form stays open");+ assert.strictEqual(editor.value, original, "no partial update");+ assert.dom(".form-kit__errors").exists("validation is shown");+ });+ }+);diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-artifact-share-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-artifact-share-test.gjsnew file mode 100644index 00000000000..02daf9dfd8a--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-artifact-share-test.gjs@@ -0,0 +1,512 @@+import { click, find, render, settled, waitUntil } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import ModalContainer from "discourse/components/modal-container";+import DialogHolder from "discourse/dialog-holder/components/dialog-holder";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { i18n } from "discourse-i18n";+import AiArtifactShare from "discourse/plugins/discourse-ai/discourse/components/ai-artifact-share";++module("Integration | Component | AiArtifactShare", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.siteSettings.discourse_ai_enabled = true;+ this.siteSettings.ai_bot_enabled = true;+ this.siteSettings.ai_artifact_security = "strict";+ this.currentUser.can_share_ai_bot_conversations = true;+ });++ hooks.afterEach(() => sinon.restore());++ test("skips eligibility requests when settings or sharing capability rule out sharing", async function (assert) {+ let requests = 0;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => {+ requests++;+ return response({ can_share: true, share: null });+ }+ );+ this.currentUser.can_share_ai_bot_conversations = false;+ await render(<template><AiArtifactShare @artifactId="12" /></template>);+ assert.strictEqual(+ requests,+ 0,+ "users without sharing capability do not probe"+ );+ assert.dom(".ai-artifact-share__toggle").doesNotExist("share is hidden");++ this.currentUser.can_share_ai_bot_conversations = true;+ this.siteSettings.ai_artifact_security = "disabled";+ await render(<template><AiArtifactShare @artifactId="12" /></template>);+ assert.strictEqual(+ requests,+ 0,+ "disabled artifacts never probe eligibility"+ );+ });++ test("checks eligibility based on capability even when memberships are not visible", async function (assert) {+ let requests = 0;+ this.currentUser.visibleGroups = [];+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => {+ requests++;+ return response({ can_share: true, share: null });+ }+ );++ await render(<template><AiArtifactShare @artifactId="12" /></template>);+ assert.strictEqual(+ requests,+ 1,+ "hidden memberships do not block the probe"+ );+ assert+ .dom(".ai-artifact-share__toggle")+ .exists("server authorizes sharing");+ });++ test("does not offer sharing without server eligibility", async function (assert) {+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => response({ can_share: false, share: null })+ );++ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="12" />+ </template>+ );+ assert.dom(".ai-artifact-share__toggle").doesNotExist("share stays hidden");+ });++ test("stays silent when the passive eligibility check fails", async function (assert) {+ const alert = sinon.stub(this.owner.lookup("service:dialog"), "alert");+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => response(404, { errors: ["Not found"] })+ );+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/13.json",+ () => response(500, { errors: ["Internal server error"] })+ );++ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="12" />+ </template>+ );+ assert+ .dom(".ai-artifact-share__toggle")+ .doesNotExist("a hidden artifact leaves sharing hidden");+ assert.false(+ alert.called,+ "a background miss does not interrupt the reader"+ );++ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="13" />+ </template>+ );+ assert+ .dom(".ai-artifact-share__toggle")+ .doesNotExist("a failing check leaves sharing hidden");+ assert.false(+ alert.called,+ "a background failure does not interrupt the reader"+ );+ });++ test("opens all share controls outside clipped cooked content", async function (assert) {+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () =>+ response({+ can_share: true,+ share: {+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 2,+ },+ })+ );++ await render(+ <template>+ <ModalContainer />+ <div class="cooked" style="overflow: hidden; height: 3em">+ <AiArtifactShare @artifactId="12" @artifactVersion="1" />+ </div>+ </template>+ );+ await click(".ai-artifact-share__toggle");++ assert+ .dom(".ai-artifact-share-modal", document)+ .exists("the share dialog renders through the modal container");+ assert.strictEqual(+ document.querySelector(".ai-artifact-share-modal").closest(".cooked"),+ null,+ "the dialog is not clipped by the cooked ancestor"+ );+ assert+ .dom(".ai-artifact-share-modal", document)+ .includesText(+ i18n("discourse_ai.ai_artifact.privacy_notice"),+ "explains privacy"+ );+ assert+ .dom(".ai-artifact-share-modal__link", document)+ .hasText("/artifact-shares/secret", "shows the actual share URL")+ .hasAttribute(+ "href",+ "/artifact-shares/secret",+ "the URL opens the shared artifact"+ );+ for (const label of [+ "Copy link",+ "Embed in post",+ "Embed on website",+ "Show in new tab",+ "Update pinned version",+ "Revoke link",+ ]) {+ assert+ .dom(".ai-artifact-share-modal__actions", document)+ .includesText(label, `${label} is available in the dialog`);+ }+ assert+ .dom(".ai-artifact-share-modal__embed-post", document)+ .hasAttribute(+ "title",+ i18n("discourse_ai.ai_artifact.embed_post_title"),+ "the post button explains copying code"+ );+ assert+ .dom(".ai-artifact-share-modal__embed-website", document)+ .hasAttribute(+ "title",+ i18n("discourse_ai.ai_artifact.embed_website_title"),+ "the website button explains copying HTML"+ );+ assert+ .dom(".ai-artifact-share-modal__actions a", document)+ .hasAttribute(+ "href",+ "/artifact-shares/secret",+ "new tab opens the share URL"+ );+ assert+ .dom(".ai-artifact-share__panel")+ .doesNotExist("no inline panel remains");+ });++ test("login-required forums explain that viewing requires sign-in", async function (assert) {+ this.siteSettings.login_required = true;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => response({ can_share: true, share: null })+ );+ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="12" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ assert+ .dom(".ai-artifact-share-modal")+ .includesText(+ "Signed-in users with the link can view this version. Your conversation stays private.",+ "private forum has a truthful notice"+ );+ assert+ .dom(".ai-artifact-share-modal")+ .doesNotIncludeText("Anyone with the link", "public notice is not used");+ });++ test("copies a standalone share key for posts and the existing URL for websites", async function (assert) {+ const writeText = sinon.stub().resolves();+ sinon.stub(window.navigator, "clipboard").get(() => ({ writeText }));+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () =>+ response({+ can_share: true,+ share: {+ share_key: "secret",+ url: "https://example.com/artifact-shares/secret",+ version: 2,+ },+ })+ );++ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="12" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ await click(".ai-artifact-share-modal__embed-post");+ await click(".ai-artifact-share-modal__embed-website");+ await click(".ai-artifact-share-modal__copy-link");++ assert.deepEqual(+ writeText.getCalls().map((call) => call.args[0]),+ [+ '[ai-artifact share="secret"]',+ '<iframe src="https://example.com/artifact-shares/secret" width="100%" height="600" frameborder="0"></iframe>',+ "https://example.com/artifact-shares/secret",+ ],+ "the post tag uses only the share key, while the website and link keep the supplied absolute URL"+ );+ });++ test("creates a standalone link immediately when Create link is clicked", async function (assert) {+ let creations = 0;+ let postedVersion;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => response({ can_share: true, share: null })+ );+ pretender.post(+ "/discourse-ai/ai-bot/artifact-shares/12.json",+ (request) => {+ creations++;+ postedVersion = new URLSearchParams(request.requestBody).get("version");+ return response({+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 0,+ });+ }+ );++ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="12" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ assert.strictEqual(+ creations,+ 0,+ "opening the modal does not publish anything"+ );+ assert+ .dom(".ai-artifact-share-modal")+ .includesText("conversation", "privacy is explained");++ await click(".ai-artifact-share-modal__create");+ assert.strictEqual(creations, 1, "the owner deliberately creates the link");+ assert.strictEqual(postedVersion, "0", "the original version is explicit");+ assert+ .dom(".ai-artifact-share-modal a[target='_blank']")+ .exists("new tab uses the share URL");+ await click(".ai-artifact-share-modal .modal-close");+ await click(".ai-artifact-share__toggle");+ assert+ .dom(".ai-artifact-share-modal__actions")+ .exists("reopening retains the newly created link");+ });++ test("keeps creation available when the server refuses a changed version", async function (assert) {+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () => response({ can_share: true, share: null })+ );+ pretender.post("/discourse-ai/ai-bot/artifact-shares/12.json", () =>+ response(409, { error: "Another version is already shared" })+ );++ await render(+ <template>+ <ModalContainer /><AiArtifactShare @artifactId="12" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ await click(".ai-artifact-share-modal__create");+ assert+ .dom(".ai-artifact-share-modal__create")+ .exists("a failed creation can be retried")+ .isNotDisabled("creation is available after the request finishes");+ assert+ .dom(".ai-artifact-share-modal__actions")+ .doesNotExist("copy controls stay hidden after a failed create");+ });++ test("revokes the link and keeps the create state when reopened", async function (assert) {+ let revocations = 0;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () =>+ response({+ can_share: true,+ share: {+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 0,+ },+ })+ );+ pretender.delete("/discourse-ai/ai-bot/artifact-shares/secret.json", () => {+ revocations++;+ return response({});+ });++ await render(+ <template>+ <ModalContainer /><DialogHolder /><AiArtifactShare @artifactId="12" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ assert+ .dom(".ai-artifact-share-modal__revoke.btn-danger")+ .exists("destructive action is red");+ await click(".ai-artifact-share-modal__revoke");+ assert+ .dom("#dialog-title")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_standalone_title")+ );+ assert+ .dom(".dialog-body")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_standalone_message")+ );+ assert.strictEqual(revocations, 0, "no deletion before confirmation");+ assert+ .dom(".ai-artifact-share-modal__copy-link")+ .isDisabled("copy is blocked while confirming");+ assert+ .dom(".ai-artifact-share-modal__update")+ .isDisabled("update is blocked while confirming");+ await click(".dialog-footer .btn-default");+ assert.strictEqual(revocations, 0, "cancel retains the link");+ assert.dom(".ai-artifact-share-modal__link").exists("link remains visible");+ await click(".ai-artifact-share-modal__revoke");+ await click(".dialog-footer .btn-danger");+ assert.strictEqual(revocations, 1, "confirmation revokes once");+ assert+ .dom(".ai-artifact-share-modal__create")+ .exists("creation becomes available without leaving the dialog");+ await click(".ai-artifact-share-modal .modal-close");+ await click(".ai-artifact-share__toggle");+ assert+ .dom(".ai-artifact-share-modal__create")+ .exists("the revoked link is not restored on reopening");+ });++ test("an in-flight pin update blocks copy and revoke until it completes", async function (assert) {+ let respond;+ let updates = 0;+ let revocations = 0;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () =>+ response({+ can_share: true,+ share: {+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 0,+ },+ })+ );+ pretender.put("/discourse-ai/ai-bot/artifact-shares/secret.json", () => {+ updates++;+ return new Promise((resolve) => {+ respond = resolve;+ });+ });+ pretender.delete("/discourse-ai/ai-bot/artifact-shares/secret.json", () => {+ revocations++;+ return response({});+ });+ await render(+ <template>+ <ModalContainer /><DialogHolder /><AiArtifactShare @artifactId="12" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ find(".ai-artifact-share-modal__update").click();+ await waitUntil(() => updates === 1);+ assert+ .dom(".ai-artifact-share-modal__copy-link")+ .isDisabled("copy is blocked");+ assert+ .dom(".ai-artifact-share-modal__revoke")+ .isDisabled("revoke is blocked");+ find(".ai-artifact-share-modal__update").click();+ find(".ai-artifact-share-modal__revoke").click();+ assert.strictEqual(updates, 1, "a second update is not sent");+ assert.strictEqual(revocations, 0, "no concurrent revoke is sent");+ respond(+ response({+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 0,+ })+ );+ await settled();+ assert+ .dom(".ai-artifact-share-modal__copy-link")+ .isNotDisabled("copy returns when settled");+ });++ test("updates a link to the older version being viewed, not the newer version", async function (assert) {+ let updatedVersion;+ pretender.get(+ "/discourse-ai/ai-bot/artifact-shares/eligibility/12.json",+ () =>+ response({+ can_share: true,+ share: {+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 2,+ },+ })+ );+ pretender.put(+ "/discourse-ai/ai-bot/artifact-shares/secret.json",+ (request) => {+ updatedVersion = new URLSearchParams(request.requestBody).get(+ "version"+ );+ return response({+ share_key: "secret",+ url: "/artifact-shares/secret",+ version: 1,+ });+ }+ );++ await render(+ <template>+ <ModalContainer />+ <AiArtifactShare @artifactId="12" @artifactVersion="1" />+ </template>+ );+ await click(".ai-artifact-share__toggle");+ await click(".ai-artifact-share-modal__actions button:nth-of-type(4)");+ assert.strictEqual(+ updatedVersion,+ "1",+ "update pins the older viewed version"+ );+ assert+ .dom(".ai-artifact-share-modal__link")+ .hasText("/artifact-shares/secret", "pinning does not change the URL");+ assert.strictEqual(+ this.owner.lookup("service:toasts").activeToasts.at(-1)?.options.data+ .message,+ i18n("discourse_ai.ai_artifact.pin_updated"),+ "pin update shows a translated toast"+ );+ });+});diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-artifact-shared-runtime-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-artifact-shared-runtime-test.gjsnew file mode 100644index 00000000000..78960ea3f40--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-artifact-shared-runtime-test.gjs@@ -0,0 +1,178 @@+import { click, findAll, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import { restoreBaseUri, setPrefix } from "discourse/lib/get-url";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import AiArtifact from "discourse/plugins/discourse-ai/discourse/components/ai-artifact";++module("Integration | Component | AiArtifact", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.siteSettings.ai_artifact_security = "lax";+ });++ hooks.afterEach(() => restoreBaseUri());++ test("uses the share endpoint ahead of source id/version, with site prefix and no eligibility check", async function (assert) {+ setPrefix("/forum");+ this.owner.lookup("service:current-user").can_share_ai_bot_conversations =+ true;++ await render(+ <template>+ <AiArtifact+ @artifactId="12"+ @artifactVersion="3"+ @dataAttributes={{hash data-trace="safe"}}+ @shareKey="key_ABC-123"+ />+ </template>+ );++ assert+ .dom(".ai-artifact__wrapper iframe")+ .hasAttribute(+ "src",+ "/forum/discourse-ai/ai-bot/artifact-shares/key_ABC-123/forum",+ "the native snapshot endpoint wins over a source id and version"+ )+ .hasAttribute("data-trace", "safe", "other metadata reaches the iframe")+ .doesNotHaveAttribute(+ "data-ai-artifact-share-key",+ "the secret is not copied as iframe metadata"+ );+ assert.dom(".ai-artifact-share").doesNotExist("no share probe is mounted");+ });++ test("strict and hybrid retain click-to-run, height, and fullscreen per key", async function (assert) {+ this.siteSettings.ai_artifact_security = "strict";+ await render(+ <template>+ <AiArtifact @artifactHeight="620" @shareKey="first" />+ <AiArtifact @artifactHeight="440" @shareKey="second" />+ </template>+ );+ assert+ .dom(".ai-artifact__wrapper iframe")+ .doesNotExist("strict mode gates execution");+ assert+ .dom(".ai-artifact__wrapper:first-child")+ .hasAttribute("style", /height: 620px/, "height is retained");+ await click(+ ".ai-artifact__wrapper:first-child .ai-artifact__click-to-run button"+ );+ assert+ .dom(".ai-artifact__wrapper iframe")+ .exists({ count: 1 }, "click runs one embed")+ .hasAttribute(+ "src",+ "/discourse-ai/ai-bot/artifact-shares/first/forum",+ "a share key alone loads the native snapshot"+ );+ assert.dom(".ai-artifact-share").doesNotExist("keyed embeds never probe");+ await click(+ ".ai-artifact__wrapper:first-child .ai-artifact__expand-button"+ );+ assert+ .dom(".ai-artifact__expanded")+ .exists({ count: 1 }, "one embed expands");+ window.dispatchEvent(+ new PopStateEvent("popstate", { state: history.state })+ );+ await settled();+ assert+ .dom(".ai-artifact__expanded")+ .exists({ count: 1 }, "history targets only the first key");+ assert.strictEqual(findAll(".ai-artifact__expanded iframe").length, 1);+ history.back();+ await settled();++ this.siteSettings.ai_artifact_security = "hybrid";+ await render(+ <template>+ <AiArtifact @autorun={{true}} @shareKey="third" />+ <AiArtifact @shareKey="fourth" />+ </template>+ );+ assert+ .dom(".ai-artifact__wrapper iframe")+ .exists({ count: 1 }, "hybrid autorun works");+ assert+ .dom(".ai-artifact__click-to-run")+ .exists({ count: 1 }, "hybrid defaults to click");+ });++ test("source versions still render and legacy fullscreen history matches only source embeds", async function (assert) {+ await render(+ <template>+ <AiArtifact @artifactId="12" @artifactVersion="3" />+ <AiArtifact @shareKey="keyed" />+ </template>+ );+ assert+ .dom(".ai-artifact__wrapper:first-child iframe")+ .hasAttribute(+ "src",+ "/discourse-ai/ai-bot/artifacts/12/3",+ "a source version keeps its original endpoint"+ );++ window.dispatchEvent(+ new PopStateEvent("popstate", { state: { artifactId: "12" } })+ );+ await settled();+ assert+ .dom(".ai-artifact__expanded")+ .exists({ count: 1 }, "legacy history expands only the source embed");+ assert+ .dom(".ai-artifact__wrapper:first-child")+ .hasClass("ai-artifact__expanded", "the source owns this history state");+ });++ test("zero and absent versions use the base source URL while positive versions retain their path", async function (assert) {+ await render(+ <template>+ <AiArtifact @artifactId="12" @artifactVersion={{0}} />+ <AiArtifact @artifactId="12" @artifactVersion="0" />+ <AiArtifact @artifactId="12" @artifactVersion="" />+ <AiArtifact @artifactId="12" @artifactVersion={{3}} />+ <AiArtifact @artifactId="12" @artifactVersion="3" />+ </template>+ );++ for (const index of [1, 2, 3]) {+ assert+ .dom(`.ai-artifact__wrapper:nth-child(${index}) iframe`)+ .hasAttribute(+ "src",+ "/discourse-ai/ai-bot/artifacts/12",+ "zero and absent versions load the base source"+ );+ }+ for (const index of [4, 5]) {+ assert+ .dom(`.ai-artifact__wrapper:nth-child(${index}) iframe`)+ .hasAttribute(+ "src",+ "/discourse-ai/ai-bot/artifacts/12/3",+ "positive versions load their source revision"+ );+ }+ });++ test("malformed identifiers never construct source or share URL", async function (assert) {+ const overlongKey = "a".repeat(129);+ await render(+ <template>+ <AiArtifact @artifactId="12" @shareKey={{overlongKey}} />+ <AiArtifact @artifactId="12" @shareKey="../escape" />+ <AiArtifact @artifactId="12" @shareKey="" />+ <AiArtifact @artifactId="https://evil.example" />+ <AiArtifact @artifactId="12" @artifactVersion="../../escape" />+ </template>+ );+ assert+ .dom(".ai-artifact__wrapper iframe")+ .doesNotExist("neither URL is opened");+ });+});diff --git a/plugins/discourse-ai/test/javascripts/integration/components/share-full-topic-modal-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/share-full-topic-modal-test.gjsnew file mode 100644index 00000000000..259297aed35--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/share-full-topic-modal-test.gjs@@ -0,0 +1,102 @@+import { click, find, render, settled, waitUntil } from "@ember/test-helpers";+import { module, test } from "qunit";+import ModalContainer from "discourse/components/modal-container";+import DialogHolder from "discourse/dialog-holder/components/dialog-holder";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { i18n } from "discourse-i18n";+import ShareFullTopicModal from "discourse/plugins/discourse-ai/discourse/components/modal/share-full-topic-modal";++module(+ "Integration | Component | Modal | ShareFullTopicModal",+ function (hooks) {+ setupRenderingTest(hooks);++ test("cancel retains the conversation key and confirmation deletes it once", async function (assert) {+ let deletes = 0;+ pretender.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/shared.json",+ () => {+ deletes++;+ return response({});+ }+ );+ await render(<template><ModalContainer /><DialogHolder /></template>);+ this.owner.lookup("service:modal").show(ShareFullTopicModal, {+ model: { share_key: "shared", topic_id: 42, context: [] },+ });+ await settled();++ assert+ .dom(".ai-share-full-topic-modal .btn-danger")+ .exists("delete is red");+ await click(".ai-share-full-topic-modal .btn-danger");+ assert+ .dom("#dialog-title")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_title")+ );+ assert+ .dom(".dialog-body")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_message")+ );+ assert+ .dom(".dialog-footer .btn-danger")+ .hasText(i18n("discourse_ai.ai_artifact.revoke_conversation"));+ assert+ .dom(".ai-share-full-topic-modal .confirm")+ .isDisabled("sharing blocked during confirmation");+ assert.strictEqual(deletes, 0, "opening confirmation does not delete");+ await click(".dialog-footer .btn-default");+ assert.strictEqual(deletes, 0, "cancel does not delete");+ assert+ .dom(".ai-share-full-topic-modal .btn-danger")+ .exists("cancel retains the key");+ await click(".ai-share-full-topic-modal .btn-danger");+ await click(".dialog-footer .btn-danger");+ assert.strictEqual(deletes, 1, "confirmation deletes once");+ assert+ .dom(".ai-share-full-topic-modal .btn-danger")+ .doesNotExist("deleted key is cleared");+ });+ test("pending deletion cannot overlap with share or a second deletion", async function (assert) {+ let respond;+ let deletes = 0;+ let shares = 0;+ pretender.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/shared.json",+ () => {+ deletes++;+ return new Promise((resolve) => {+ respond = resolve;+ });+ }+ );+ pretender.post("/discourse-ai/ai-bot/shared-ai-conversations", () => {+ shares++;+ return response({ share_key: "new" });+ });+ await render(<template><ModalContainer /><DialogHolder /></template>);+ this.owner.lookup("service:modal").show(ShareFullTopicModal, {+ model: { share_key: "shared", topic_id: 42, context: [] },+ });+ await settled();+ await click(".ai-share-full-topic-modal .btn-danger");+ find(".dialog-footer .btn-danger").click();+ await waitUntil(() => deletes === 1);+ assert+ .dom(".ai-share-full-topic-modal .confirm")+ .isDisabled("share is disabled");+ assert+ .dom(".ai-share-full-topic-modal .btn-danger")+ .isDisabled("delete is disabled");+ find(".ai-share-full-topic-modal .confirm").click();+ find(".ai-share-full-topic-modal .btn-danger").click();+ assert.strictEqual(shares, 0, "no concurrent sharing");+ assert.strictEqual(deletes, 1, "no duplicate deletion");+ respond(response({}));+ await settled();+ });+ }+);diff --git a/plugins/discourse-ai/test/javascripts/integration/components/shared-artifacts-list-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/shared-artifacts-list-test.gjsnew file mode 100644index 00000000000..a4a8f20cf9f--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/shared-artifacts-list-test.gjs@@ -0,0 +1,844 @@+import { click, find, render, settled, waitUntil } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DialogHolder from "discourse/dialog-holder/components/dialog-holder";+import { getAbsoluteURL } from "discourse/lib/get-url";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";+import {+ disableLoadMoreObserver,+ enableLoadMoreObserver,+} from "discourse/ui-kit/d-load-more";+import { i18n } from "discourse-i18n";+import SharedArtifactsList from "discourse/plugins/discourse-ai/discourse/components/shared-artifacts-list";++function listData(items, { hasMore = false, nextCursor = null } = {}) {+ return { items, has_more: hasMore, next_cursor: nextCursor };+}++function share(name, shareKey, available = true) {+ return {+ id: `standalone-${shareKey}`,+ type: "standalone",+ name,+ url: `/discourse-ai/ai-bot/artifact-shares/${shareKey}`,+ share_key: shareKey,+ version: 0,+ available,+ created_at: "2026-09-21T12:00:00Z",+ };+}++function conversation(name, id, shareKey = `conversation-${id}`) {+ return {+ id: `conversation-${id}`,+ type: "conversation",+ name,+ url: `/discourse-ai/ai-bot/shared-ai-conversations/${shareKey}`,+ embed_url: `/artifacts/${100 + id}/2/embed`,+ available: true,+ share_key: shareKey,+ topic_id: id,+ artifact_id: 100 + id,+ artifact_version: 2,+ created_at: "2026-09-20T12:00:00Z",+ };+}++function deferredRequest(method, path) {+ let resolveRequest;+ let received = 0;+ pretender[method](path, () => {+ received++;+ return new Promise((resolve) => {+ resolveRequest = resolve;+ });+ });++ return {+ get count() {+ return received;+ },+ respond(body) {+ resolveRequest(response(body));+ },+ };+}++// DOM helpers wait for pending requests; dispatch directly to test overlapping actions.+function activate(element) {+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+}++module("Integration | Component | SharedArtifactsList", function (hooks) {+ setupRenderingTest(hooks);++ hooks.afterEach(function () {+ disableLoadMoreObserver();+ });++ test("renders one chronological mixed list with compact cards and no mounted previews", async function (assert) {+ this.data = listData([share("First", "first"), conversation("Second", 42)]);+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ assert+ .dom("#shared-artifacts-heading")+ .hasText("Shared AI artifacts", "page title");+ assert+ .dom(".shared-artifacts")+ .hasAttribute(+ "aria-labelledby",+ "shared-artifacts-heading",+ "title labels the section"+ );+ assert.dom(".shared-artifacts__list").exists({ count: 1 }, "one list");+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "both share types are in the same list");+ assert.dom(".shared-artifacts__card:first-child h3").hasText("First");+ assert.dom(".shared-artifacts__card:last-child h3").hasText("Second");+ assert+ .dom(".shared-artifacts iframe")+ .doesNotExist("neither share type mounts an artifact document");+ assert+ .dom(".shared-artifacts__preview")+ .doesNotExist("there are no preview containers");+ assert+ .dom('.shared-artifacts__filters [aria-pressed="true"]')+ .hasText("All", "all shares selected by default");+ assert+ .dom(+ ".shared-artifacts__card:first-child .shared-artifacts__actions button"+ )+ .exists({ count: 4 }, "standalone has four direct actions");+ assert+ .dom(+ ".shared-artifacts__card:last-child .shared-artifacts__actions button"+ )+ .exists({ count: 4 }, "conversation has the same four direct actions");+ for (const action of ["copy-link", "embed-post", "embed-website"]) {+ assert+ .dom(`.shared-artifacts__${action}`)+ .exists({ count: 2 }, `${action} is explicit on both cards`);+ }+ assert+ .dom(".shared-artifacts__embed-post")+ .hasAttribute(+ "title",+ i18n("discourse_ai.ai_artifact.embed_post_title"),+ "post action explains that it copies code"+ );+ assert+ .dom(".shared-artifacts__embed-website")+ .hasAttribute(+ "title",+ i18n("discourse_ai.ai_artifact.embed_website_title"),+ "website action explains that it copies HTML"+ );+ assert+ .dom(".shared-artifacts__revoke.btn-danger")+ .exists({ count: 2 }, "both revoke actions are red");+ assert+ .dom(".shared-artifacts__card:last-child .shared-artifacts__revoke")+ .hasText(+ i18n("discourse_ai.ai_artifact.revoke_conversation"),+ "conversation revoke identifies its scope"+ );+ assert+ .dom(".shared-artifacts__actions [aria-expanded]")+ .doesNotExist("there are no manage disclosures");+ assert+ .dom(".shared-artifacts__notice")+ .doesNotExist("redundant privacy notice is removed");+ assert+ .dom(".shared-artifacts__footnote")+ .doesNotExist("redundant footnote is removed");+ });++ test("copies explicit post tags and absolute website embeds for both share types", async function (assert) {+ const writeText = sinon.stub().resolves();+ sinon.stub(window.navigator, "clipboard").get(() => ({ writeText }));+ const external = {+ ...conversation("External", 43),+ url: "https://example.com/conversation",+ embed_url: "https://example.com/artifacts/143/embed",+ artifact_version: null,+ };+ this.data = listData([+ share("Standalone", "first"),+ conversation("Conversation", 42),+ external,+ {+ ...conversation("Original", 44),+ artifact_version: 0,+ embed_url: "/artifacts/144/embed",+ },+ ]);+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ for (let card = 1; card <= 4; card++) {+ for (const action of ["copy-link", "embed-post", "embed-website"]) {+ await click(+ `.shared-artifacts__card:nth-child(${card}) .shared-artifacts__${action}`+ );+ }+ }++ const standaloneURL = getAbsoluteURL(+ "/discourse-ai/ai-bot/artifact-shares/first"+ );+ const conversationURL = getAbsoluteURL(+ "/discourse-ai/ai-bot/shared-ai-conversations/conversation-42"+ );+ const artifactURL = getAbsoluteURL("/artifacts/142/2/embed");+ const embed = (url) =>+ `<iframe src="${url}" width="100%" height="600" frameborder="0"></iframe>`;+ assert.strictEqual(+ writeText.getCall(2).args[0],+ embed(standaloneURL),+ "the copied website iframe keeps the anonymous public share URL, not the native /forum endpoint"+ );+ assert.deepEqual(+ writeText.getCalls().map((call) => call.args[0]),+ [+ standaloneURL,+ '[ai-artifact share="first"]',+ embed(standaloneURL),+ conversationURL,+ '[ai-artifact id="142" version="2"]',+ embed(artifactURL),+ "https://example.com/conversation",+ '[ai-artifact id="143"]',+ embed("https://example.com/artifacts/143/embed"),+ getAbsoluteURL(+ "/discourse-ai/ai-bot/shared-ai-conversations/conversation-44"+ ),+ '[ai-artifact id="144"]',+ embed(getAbsoluteURL("/artifacts/144/embed")),+ ],+ "post tags use share keys or artifact IDs, never URLs; website embeds retain their existing URLs"+ );+ });++ test("unavailable conversations only offer confirmed revoke", async function (assert) {+ let deletes = 0;+ pretender.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/conversation-42.json",+ () => {+ deletes++;+ return response({});+ }+ );+ this.data = listData([{ ...conversation("Gone", 42), available: false }]);+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} /><DialogHolder />+ </template>+ );+ assert.dom(".shared-artifacts__card h3 a").doesNotExist("no dead link");+ assert.dom(".shared-artifacts__unavailable").exists("shows unavailability");+ assert+ .dom(".shared-artifacts__actions button")+ .exists({ count: 1 }, "revoke only");+ await click(".shared-artifacts__revoke");+ assert+ .dom("#dialog-title")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_title")+ );+ assert.strictEqual(deletes, 0, "confirmation does not delete");+ await click(".dialog-footer .btn-default");+ assert.strictEqual(deletes, 0, "cancel retains share");+ await click(".shared-artifacts__revoke");+ await click(".dialog-footer .btn-danger");+ assert.strictEqual(deletes, 1, "confirm deletes once");+ });++ test("keeps unavailable standalone shares revocable without a dead link", async function (assert) {+ let revokedPath;+ pretender.delete(+ "/discourse-ai/ai-bot/artifact-shares/gone.json",+ (request) => {+ revokedPath = request.url;+ return response({});+ }+ );++ this.data = listData([share("Orphan", "gone", false)]);+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );++ assert.dom(".shared-artifacts__unavailable").exists("unavailable state");+ assert.dom(".shared-artifacts__card a").doesNotExist("no dead link");+ assert+ .dom(".shared-artifacts__actions button")+ .exists({ count: 1 }, "unavailable link can only be revoked");++ await click(".shared-artifacts__revoke");+ assert+ .dom("#dialog-title")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_standalone_title")+ );+ assert+ .dom(".dialog-body")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_standalone_message")+ );+ assert+ .dom(".dialog-footer .btn-danger")+ .hasText(i18n("discourse_ai.ai_artifact.revoke"));+ assert.strictEqual(+ revokedPath,+ undefined,+ "opening confirmation does not revoke the link"+ );+ await click(".dialog-footer .btn-danger");++ assert.strictEqual(+ revokedPath,+ "/discourse-ai/ai-bot/artifact-shares/gone.json",+ "the owner can revoke the link"+ );+ assert.dom(".shared-artifacts__card").doesNotExist("revoked card removed");+ });++ test("canceling standalone revoke keeps the feed and cursor without a request", async function (assert) {+ let deletes = 0;+ const pages = [];+ const cursor = { after: ["2026-09-21", 4] };+ pretender.delete("/discourse-ai/ai-bot/artifact-shares/first.json", () => {+ deletes++;+ return response({});+ });+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ pages.push(request.queryParams);+ return response(listData([share("Next", "next")]));+ });+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: cursor,+ });+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );++ await click(".shared-artifacts__revoke");+ assert.strictEqual(deletes, 0, "opening dialog sends no DELETE");+ await observations.at(-1).trigger();+ assert.deepEqual(pages, [], "observer cannot load while confirming");+ await click(".dialog-footer .btn-default");+ assert.dom("#dialog-holder").doesNotExist("cancel closes the dialog");+ assert.strictEqual(deletes, 0, "cancel sends no DELETE");+ assert.deepEqual(pages, [], "cancel sends no list request");+ assert.dom(".shared-artifacts__card h3").hasText("First", "card remains");++ await observations.at(-1).trigger();+ assert.deepEqual(+ pages,+ [{ type: "all", order: "newest", cursor: JSON.stringify(cursor) }],+ "the observer resumes with the original cursor after cancel"+ );+ });++ test("canceling conversation revoke keeps sibling and standalone shares", async function (assert) {+ let deletes = 0;+ pretender.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/shared.json",+ () => {+ deletes++;+ return response({});+ }+ );+ this.data = listData([+ share("Standalone", "shared"),+ conversation("First", 42, "shared"),+ conversation("Second", 43, "shared"),+ ]);+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );++ await click(+ ".shared-artifacts__card:nth-child(2) .shared-artifacts__revoke"+ );+ assert.strictEqual(deletes, 0, "opening dialog sends no DELETE");+ await click(".dialog-footer .btn-default");+ assert.strictEqual(deletes, 0, "cancel sends no DELETE");+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 3 }, "all conversation and standalone cards remain");+ assert.dom("#dialog-holder").doesNotExist("cancel closes the dialog");+ });++ test("direct conversation revoke removes sibling cards but not standalone shares", async function (assert) {+ const deletion = deferredRequest(+ "delete",+ "/discourse-ai/ai-bot/shared-ai-conversations/shared.json"+ );+ this.data = listData([+ share("Standalone of the same artifact", "shared"),+ conversation("First conversation artifact", 42, "shared"),+ conversation("Second conversation artifact", 43, "shared"),+ conversation("Another conversation", 44),+ ]);+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );++ const firstRevoke = find(+ ".shared-artifacts__card:nth-child(2) .shared-artifacts__revoke"+ );+ activate(firstRevoke);+ activate(+ find(".shared-artifacts__card:nth-child(3) .shared-artifacts__revoke")+ );+ await settled();+ assert+ .dom("#dialog-title")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_title")+ );+ assert+ .dom(".dialog-body")+ .hasText(+ i18n("discourse_ai.ai_artifact.confirm_revoke_conversation_message")+ );+ assert+ .dom(".dialog-footer .btn-danger")+ .hasText(i18n("discourse_ai.ai_artifact.revoke_conversation"));+ assert.strictEqual(+ deletion.count,+ 0,+ "no conversation DELETE before confirm"+ );+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 4 }, "all cards stay until confirmation");+ activate(find(".dialog-footer .btn-danger"));+ await waitUntil(() => deletion.count === 1);+ assert.strictEqual(+ deletion.count,+ 1,+ "only one conversation DELETE starts"+ );+ assert.true(firstRevoke.disabled, "revoke is disabled while loading");+ assert+ .dom(".shared-artifacts__card:first-child .shared-artifacts__revoke")+ .isDisabled("standalone revoke cannot race the conversation request");++ deletion.respond({});+ await settled();+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "all cards from this conversation are removed");+ assert+ .dom(".shared-artifacts__card:first-child h3")+ .hasText("Standalone of the same artifact", "standalone card remains");+ assert+ .dom(".shared-artifacts__card:last-child h3")+ .hasText("Another conversation", "other conversation remains");+ });++ test("filtering replaces the list and resets the cursor, including after pagination", async function (assert) {+ const requests = [];+ const cursor = { after: ["2026-09-21", 9], seen: [3, 4] };+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ requests.push(request.queryParams);+ if (request.queryParams.cursor) {+ return response(listData([conversation("Next", 43)]));+ }+ return response(listData([share("Filtered", "filtered")]));+ });+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: cursor,+ });+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ await observations.at(-1).trigger();+ assert.deepEqual(+ requests[0],+ { type: "all", order: "newest", cursor: JSON.stringify(cursor) },+ "the first page uses the initial cursor"+ );+ await click(".shared-artifacts__filters button:nth-child(2)");+ assert.deepEqual(+ requests[1],+ { type: "standalone", order: "newest" },+ "filter change starts at the first page"+ );+ assert+ .dom('.shared-artifacts__filters [aria-pressed="true"]')+ .hasText("Standalone", "filter is selected after success");+ assert.dom(".shared-artifacts__card h3").hasText("Filtered");+ });++ test("sort reloads from the first page using the active filter", async function (assert) {+ const requests = [];+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ requests.push(request.queryParams);+ return response(listData([conversation("Oldest", 42)]));+ });+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: { key: "old cursor" },+ });+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ await click(".shared-artifacts__filters button:nth-child(3)");+ await click(".shared-artifacts__sort");++ assert.deepEqual(+ requests,+ [+ { type: "conversation", order: "newest" },+ { type: "conversation", order: "oldest" },+ ],+ "filter and sort both reload without passing the old cursor"+ );+ assert+ .dom(".shared-artifacts__sort")+ .hasText(+ i18n("discourse_ai.ai_artifact.oldest_first"),+ "order changes after successful reload"+ );+ assert.dom(".shared-artifacts__card h3").hasText("Oldest");+ });++ test("an in-flight filter reload blocks duplicate filters and sorting", async function (assert) {+ const requests = deferredRequest(+ "get",+ "/discourse-ai/ai-bot/artifact-shares.json"+ );+ this.data = listData([share("First", "first")]);+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ const filter = find(".shared-artifacts__filters button:nth-child(2)");+ activate(filter);+ activate(filter);+ activate(find(".shared-artifacts__sort"));+ await waitUntil(() => requests.count === 1);+ assert.strictEqual(requests.count, 1, "only one reload starts");+ assert.true(filter.disabled, "filters are disabled in flight");+ assert+ .dom(".shared-artifacts__sort")+ .isDisabled("sort is disabled in flight");+ assert+ .dom('.shared-artifacts__filters [aria-pressed="true"]')+ .hasText("All", "the selection changes only on success");+ assert+ .dom(".shared-artifacts__card h3")+ .hasText("First", "cards stay visible");++ requests.respond(listData([share("Filtered", "filtered")]));+ await settled();+ assert.dom(".shared-artifacts__card h3").hasText("Filtered");+ assert+ .dom('.shared-artifacts__filters [aria-pressed="true"]')+ .hasText("Standalone", "selection commits after response");+ });++ test("an in-flight sort reload is not requested twice", async function (assert) {+ const requests = deferredRequest(+ "get",+ "/discourse-ai/ai-bot/artifact-shares.json"+ );+ this.data = listData([share("First", "first")]);+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ const sort = find(".shared-artifacts__sort");+ activate(sort);+ activate(sort);+ await waitUntil(() => requests.count === 1);+ assert.strictEqual(requests.count, 1, "only one sort request starts");+ assert.true(sort.disabled, "sort is disabled while loading");+ assert+ .dom(".shared-artifacts__sort")+ .hasText(+ i18n("discourse_ai.ai_artifact.newest_first"),+ "order does not change before the response"+ );++ requests.respond(listData([share("Oldest", "oldest")]));+ await settled();+ assert.dom(".shared-artifacts__card h3").hasText("Oldest");+ assert+ .dom(".shared-artifacts__sort")+ .hasText(+ i18n("discourse_ai.ai_artifact.oldest_first"),+ "order commits after response"+ );+ });++ test("in-flight requests guard filter, sort, pagination and double revoke", async function (assert) {+ const deletion = deferredRequest(+ "delete",+ "/discourse-ai/ai-bot/artifact-shares/first.json"+ );+ const pages = [];+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ pages.push(request.queryParams);+ return response(listData([]));+ });+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: { key: "keep" },+ });+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );+ const revokeButton = find(".shared-artifacts__revoke");+ activate(revokeButton);+ activate(revokeButton);+ await settled();+ assert+ .dom(".dialog-container")+ .exists({ count: 1 }, "one confirmation opens");+ assert.strictEqual(deletion.count, 0, "duplicate clicks send no DELETE");+ activate(find(".dialog-footer .btn-danger"));+ await waitUntil(() => deletion.count === 1);+ assert.strictEqual(deletion.count, 1, "only one deletion is requested");+ assert.true(revokeButton.disabled, "revoke is disabled in flight");+ assert.dom(".shared-artifacts__sort").isDisabled("sort cannot race revoke");+ assert+ .dom(".shared-artifacts__filters button")+ .isDisabled("filter cannot race revoke");+ activate(find(".shared-artifacts__sort"));+ activate(find(".shared-artifacts__filters button:nth-child(2)"));+ const pendingScroll = observations.at(-1).trigger();+ await new Promise((resolve) => setTimeout(resolve, 150));+ assert.deepEqual(pages, [], "other actions do not start requests");++ deletion.respond({});+ await pendingScroll;+ assert.dom(".shared-artifacts__card").doesNotExist("the item is removed");+ assert.deepEqual(pages, [], "revoke does not reset or reload pagination");+ });++ test("revoke retains the cursor for the next page", async function (assert) {+ const cursor = { timestamp: "2026-09-21", ids: [42, 91] };+ const requests = [];+ pretender.delete("/discourse-ai/ai-bot/artifact-shares/first.json", () =>+ response({})+ );+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ requests.push(request.queryParams);+ return response(listData([conversation("Unseen", 44)]));+ });+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData(+ [share("First", "first"), conversation("Second", 42)],+ {+ hasMore: true,+ nextCursor: cursor,+ }+ );+ await render(+ <template>+ <SharedArtifactsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );+ await click(+ ".shared-artifacts__card:first-child .shared-artifacts__revoke"+ );+ assert.deepEqual(requests, [], "no pagination request before confirming");+ await click(".dialog-footer .btn-danger");+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 1 }, "revoke removes only the first card");++ await observations.at(-1).trigger();+ assert.deepEqual(+ requests,+ [{ type: "all", order: "newest", cursor: JSON.stringify(cursor) }],+ "pagination keeps the same cursor after deletion"+ );+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "the next page is appended");+ });++ test("failed filter and sort requests leave the current feed and selection untouched", async function (assert) {+ let attempts = 0;+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", () => {+ attempts++;+ return response(500, { errors: ["Unavailable"] });+ });+ this.data = listData([share("First", "first")]);+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );+ await click(".shared-artifacts__filters button:nth-child(2)");+ await click(".shared-artifacts__sort");++ assert.strictEqual(attempts, 2, "both reload attempts were made");+ assert.dom(".shared-artifacts__card h3").hasText("First", "list preserved");+ assert+ .dom('.shared-artifacts__filters [aria-pressed="true"]')+ .hasText("All", "filter preserved");+ assert+ .dom(".shared-artifacts__sort")+ .hasText(+ i18n("discourse_ai.ai_artifact.newest_first"),+ "order preserved"+ );+ });++ test("observer loads an empty intermediate page and advances with the opaque cursor", async function (assert) {+ const firstCursor = { after: ["2026-09-21", 4] };+ const secondCursor = { after: ["2026-09-20", 3] };+ const requests = [];+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ requests.push(request.queryParams);+ return response(+ requests.length === 1+ ? listData([], { hasMore: true, nextCursor: secondCursor })+ : listData([conversation("Later", 43)])+ );+ });+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: firstCursor,+ });+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ await observations.at(-1).trigger();+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 1 }, "empty page does not empty or duplicate the feed");+ await observations.at(-1).trigger();+ assert.deepEqual(+ requests,+ [+ { type: "all", order: "newest", cursor: JSON.stringify(firstCursor) },+ { type: "all", order: "newest", cursor: JSON.stringify(secondCursor) },+ ],+ "each request roundtrips the cursor without interpreting it"+ );+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "next page appended");+ });++ test("a pending observer load cannot request the same page twice", async function (assert) {+ const requests = deferredRequest(+ "get",+ "/discourse-ai/ai-bot/artifact-shares.json"+ );+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: { key: "keep" },+ });+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ const firstLoad = observations.at(-1).trigger();+ await waitUntil(() => requests.count === 1);+ const secondLoad = observations.at(-1).trigger();+ await new Promise((resolve) => setTimeout(resolve, 150));+ assert.strictEqual(requests.count, 1, "only one page request is in flight");+ assert+ .dom(".shared-artifacts__filters button")+ .isDisabled("filter cannot race the page request");+ assert+ .dom(".shared-artifacts__sort")+ .isDisabled("sort cannot race the page request");++ requests.respond(listData([conversation("Next", 43)]));+ await Promise.all([firstLoad, secondLoad]);+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 2 }, "page appended once");+ });++ test("failed observer load pauses until Retry and does not drop the cursor", async function (assert) {+ const cursor = { after: ["2026-09-21", 4] };+ const requests = [];+ pretender.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {+ requests.push(request.queryParams);+ return requests.length === 1+ ? response(500, { errors: ["Unavailable"] })+ : response(listData([conversation("Recovered", 43)]));+ });+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share("First", "first")], {+ hasMore: true,+ nextCursor: cursor,+ });+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ await observations.at(-1).trigger();+ assert.dom(".shared-artifacts__retry").exists("retry is shown");+ await observations.at(-1).trigger();+ assert.strictEqual(+ requests.length,+ 1,+ "observer cannot retry automatically"+ );+ assert+ .dom(".shared-artifacts__card")+ .exists({ count: 1 }, "items preserved");++ await click(".shared-artifacts__retry");+ assert.deepEqual(+ requests,+ [+ { type: "all", order: "newest", cursor: JSON.stringify(cursor) },+ { type: "all", order: "newest", cursor: JSON.stringify(cursor) },+ ],+ "retry reuses the same cursor"+ );+ assert.dom(".shared-artifacts__retry").doesNotExist("retry clears");+ assert.dom(".shared-artifacts__card").exists({ count: 2 }, "page appended");+ });+});diff --git a/plugins/discourse-ai/test/javascripts/integration/components/shared-conversations-list-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/shared-conversations-list-test.gjsnew file mode 100644index 00000000000..4f2d4fafdb8--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/shared-conversations-list-test.gjs@@ -0,0 +1,234 @@+import { click, find, render, settled, waitUntil } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DialogHolder from "discourse/dialog-holder/components/dialog-holder";+import { getAbsoluteURL } from "discourse/lib/get-url";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";+import {+ disableLoadMoreObserver,+ enableLoadMoreObserver,+} from "discourse/ui-kit/d-load-more";+import { i18n } from "discourse-i18n";+import SharedConversationsList from "discourse/plugins/discourse-ai/discourse/components/shared-conversations-list";++function listData(items, hasMore = false, nextCursor = null) {+ return { items, has_more: hasMore, next_cursor: nextCursor };+}++function share(id, available = true) {+ return {+ id,+ share_key: `key-${id}`,+ title: `Conversation ${id}`,+ url: `/discourse-ai/ai-bot/shared-ai-conversations/key-${id}`,+ created_at: "2026-09-21T12:00:00Z",+ available,+ };+}++function activate(element) {+ element.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+}++module("Integration | Component | SharedConversationsList", function (hooks) {+ setupRenderingTest(hooks);++ hooks.afterEach(function () {+ disableLoadMoreObserver();+ });++ test("renders title, date, available links and revoke-only unavailable rows", async function (assert) {+ this.data = listData([share(1), share(2, false)]);+ await render(+ <template><SharedConversationsList @data={{this.data}} /></template>+ );++ assert+ .dom("#shared-conversations-heading")+ .hasText("Shared AI conversations");+ assert.dom(".shared-conversations__card").exists({ count: 2 });+ assert+ .dom(".shared-conversations__card:first-child h3 a")+ .hasText("Conversation 1");+ assert.dom(".shared-conversations__meta").exists({ count: 2 });+ assert.dom(".shared-conversations__card:last-child h3 a").doesNotExist();+ assert.dom(".shared-conversations__unavailable").exists();+ assert.dom(".shared-conversations__copy-link").exists({ count: 1 });+ assert.dom(".shared-conversations__revoke.btn-danger").exists({ count: 2 });+ assert.dom(".shared-conversations__actions button").exists({ count: 3 });+ assert+ .dom(".shared-conversations iframe")+ .doesNotExist("no preview or embeds");+ assert.dom(".shared-conversations__excerpt").doesNotExist("no excerpts");+ assert+ .dom(".shared-conversations__manage")+ .doesNotExist("no manage action");+ });++ test("copies the absolute link and confirms before revoking", async function (assert) {+ const writeText = sinon.stub().resolves();+ sinon.stub(window.navigator, "clipboard").get(() => ({ writeText }));+ let deletes = 0;+ pretender.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/key-1.json",+ () => {+ deletes++;+ return response({});+ }+ );+ this.data = listData([share(1)]);+ await render(+ <template>+ <SharedConversationsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );++ await click(".shared-conversations__copy-link");+ assert.strictEqual(+ writeText.lastCall.args[0],+ getAbsoluteURL(share(1).url),+ "absolute link is copied"+ );+ await click(".shared-conversations__revoke");+ assert.dom("#dialog-title").hasText("Revoke conversation share?");+ assert.strictEqual(deletes, 0, "opening the confirmation does not delete");+ await click(".dialog-footer .btn-default");+ assert.strictEqual(deletes, 0, "cancellation keeps the share");+ assert.dom(".shared-conversations__card").exists();+ await click(".shared-conversations__revoke");+ await click(".dialog-footer .btn-danger");+ assert.strictEqual(deletes, 1, "only confirmation deletes");+ assert+ .dom(".shared-conversations__empty")+ .exists("the revoked row is removed");+ });++ test("sort reloads the feed without a cursor and commits the order only on success", async function (assert) {+ const requests = [];+ pretender.get(+ "/discourse-ai/ai-bot/shared-ai-conversations.json",+ (request) => {+ requests.push(request.queryParams);+ return response(listData([share(2)]));+ }+ );+ this.data = listData([share(1)]);+ await render(+ <template><SharedConversationsList @data={{this.data}} /></template>+ );+ await click(".shared-conversations__sort");+ assert.deepEqual(requests, [{ order: "oldest" }]);+ assert.dom(".shared-conversations__card h3").hasText("Conversation 2");+ assert+ .dom(".shared-conversations__sort")+ .hasText(i18n("discourse_ai.ai_artifact.oldest_first"));+ });++ test("observer pause on confirmation resumes after cancel; failed page retries the same cursor", async function (assert) {+ const cursor = { after: ["2026-09-21", 1] };+ const requests = [];+ pretender.get(+ "/discourse-ai/ai-bot/shared-ai-conversations.json",+ (request) => {+ requests.push(request.queryParams);+ return requests.length === 1+ ? response(500, { errors: ["Unavailable"] })+ : response(listData([share(2)]));+ }+ );+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share(1)], true, cursor);+ await render(+ <template>+ <SharedConversationsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );++ await click(".shared-conversations__revoke");+ await observations.at(-1).trigger();+ assert.deepEqual(requests, [], "confirmation pauses the observer");+ await click(".dialog-footer .btn-default");+ await observations.at(-1).trigger();+ assert+ .dom(".shared-conversations__retry")+ .exists("failed page shows retry");+ await observations.at(-1).trigger();+ assert.strictEqual(requests.length, 1, "observer cannot auto-retry");+ await click(".shared-conversations__retry");+ assert.deepEqual(+ requests,+ [+ { order: "newest", cursor: JSON.stringify(cursor) },+ { order: "newest", cursor: JSON.stringify(cursor) },+ ],+ "retry retains the opaque cursor"+ );+ assert.dom(".shared-conversations__card").exists({ count: 2 });+ });++ test("in-flight page and deletion guard duplicate requests and preserve the cursor", async function (assert) {+ const cursor = { after: ["2026-09-21", 1] };+ let resolvePage;+ let pageRequests = 0;+ pretender.get("/discourse-ai/ai-bot/shared-ai-conversations.json", () => {+ pageRequests++;+ return new Promise((resolve) => (resolvePage = resolve));+ });+ let resolveDelete;+ let deleteRequests = 0;+ pretender.delete(+ "/discourse-ai/ai-bot/shared-ai-conversations/key-1.json",+ () => {+ deleteRequests++;+ return new Promise((resolve) => (resolveDelete = resolve));+ }+ );+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ this.data = listData([share(1)], true, cursor);+ await render(+ <template>+ <SharedConversationsList @data={{this.data}} />+ <DialogHolder />+ </template>+ );+ activate(find(".shared-conversations__revoke"));+ activate(find(".shared-conversations__revoke"));+ await settled();+ assert.dom(".dialog-container").exists({ count: 1 });+ activate(find(".dialog-footer .btn-danger"));+ await waitUntil(() => deleteRequests === 1);+ activate(find(".shared-conversations__sort"));+ const pendingScroll = observations.at(-1).trigger();+ await new Promise((resolve) => setTimeout(resolve, 150));+ assert.strictEqual(+ pageRequests,+ 0,+ "busy delete prevents pagination and sort"+ );+ resolveDelete(response({}));+ await pendingScroll;+ await settled();+ assert.dom(".shared-conversations__card").doesNotExist();+ const firstLoad = observations.at(-1).trigger();+ await waitUntil(() => pageRequests === 1);+ const secondLoad = observations.at(-1).trigger();+ await new Promise((resolve) => setTimeout(resolve, 150));+ assert.strictEqual(+ pageRequests,+ 1,+ "in-flight page is not requested twice"+ );+ assert.dom(".shared-conversations__sort").isDisabled();+ resolvePage(response(listData([share(2)])));+ await Promise.all([firstLoad, secondLoad]);+ assert.dom(".shared-conversations__card h3").hasText("Conversation 2");+ });+});diff --git a/plugins/discourse-ai/test/javascripts/unit/lib/ai-artifact-markdown-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/ai-artifact-markdown-test.jsnew file mode 100644index 00000000000..a58925dec1b--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/unit/lib/ai-artifact-markdown-test.js@@ -0,0 +1,282 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { cook } from "discourse/lib/text";++const enabled = { siteSettings: { discourse_ai_enabled: true } };++async function cookedMarkup(input, options = enabled) {+ return (await cook(input, options)).toString();+}++function artifactElements(markup) {+ return [+ ...new DOMParser()+ .parseFromString(markup, "text/html")+ .querySelectorAll("div.ai-artifact"),+ ];+}++module("Unit | Lib | ai-artifact-markdown", function (hooks) {+ setupTest(hooks);++ test("standalone share token produces an artifact mount point", async function (assert) {+ for (const share of ["Ab_09-z", "a".repeat(128)]) {+ const [artifact] = artifactElements(+ await cookedMarkup(`[ai-artifact share="${share}"]`)+ );++ assert.true(!!artifact, `${share} renders the artifact div`);+ assert.strictEqual(+ artifact?.getAttribute("data-ai-artifact-share-key"),+ share,+ "preserves the share key"+ );+ assert.false(+ artifact?.hasAttribute("data-ai-artifact-id"),+ "does not add an id"+ );+ }+ });++ test("id and optional version produce artifact mount points without number coercion", async function (assert) {+ for (const [input, id, version] of [+ ['[ai-artifact id="123"]', "123", null],+ ['[ai-artifact id="123" version="2"]', "123", "2"],+ ['[ai-artifact id="123" version="0"]', "123", null],+ [+ '[ai-artifact id="9999999999999999999" version="1234567890123456789"]',+ "9999999999999999999",+ "1234567890123456789",+ ],+ ]) {+ const artifacts = artifactElements(await cookedMarkup(input));+ assert.strictEqual(artifacts.length, 1, `${input} renders once`);+ assert.strictEqual(+ artifacts[0]?.getAttribute("data-ai-artifact-id"),+ id,+ `${input} preserves id digits`+ );+ assert.strictEqual(+ artifacts[0]?.getAttribute("data-ai-artifact-version"),+ version,+ `${input} preserves version digits or omits zero`+ );+ }+ });++ test("explicit autorun booleans are preserved on both embed forms", async function (assert) {+ for (const [input, identifier] of [+ [+ '[ai-artifact share="key" autorun="true"]',+ "data-ai-artifact-share-key",+ ],+ [+ '[ai-artifact autorun="false" share="key"]',+ "data-ai-artifact-share-key",+ ],+ ['[ai-artifact id="7" autorun="true"]', "data-ai-artifact-id"],+ [+ '[ai-artifact autorun="false" version="2" id="7"]',+ "data-ai-artifact-id",+ ],+ ]) {+ const artifacts = artifactElements(await cookedMarkup(input));+ const [artifact] = artifacts;+ const expected = input.includes('autorun="true"') ? "true" : "false";+ assert.strictEqual(artifacts.length, 1, `${input} renders once`);+ assert.strictEqual(+ artifact?.getAttribute(identifier),+ identifier.includes("share") ? "key" : "7",+ `${input} retains the identifier`+ );+ assert.strictEqual(+ artifact?.getAttribute("data-ai-artifact-autorun"),+ expected,+ `${input} retains the explicit autorun value`+ );+ }++ for (const input of [+ '[ai-artifact share="key"]',+ '[ai-artifact id="7" version="2"]',+ ]) {+ const [artifact] = artifactElements(await cookedMarkup(input));+ assert.false(+ artifact?.hasAttribute("data-ai-artifact-autorun"),+ `${input} has no implicit autorun attribute`+ );+ }+ });++ test("height and seamless cook as constrained compact layout attributes", async function (assert) {+ for (const [input, identifier] of [+ [+ '[ai-artifact share="key" height="2000" seamless="true"]',+ "data-ai-artifact-share-key",+ ],+ [+ '[ai-artifact id="7" height="00042" seamless="false"]',+ "data-ai-artifact-id",+ ],+ ]) {+ const [artifact] = artifactElements(await cookedMarkup(input));+ assert.true(!!artifact, `${input} cooks to an artifact`);+ assert.true(artifact.hasAttribute(identifier), "identity is retained");+ assert.strictEqual(+ artifact.getAttribute("data-ai-artifact-height"),+ input.includes("2000") ? "2000" : "42",+ "height is canonical decimal"+ );+ assert.strictEqual(+ artifact.getAttribute("data-ai-artifact-seamless"),+ input.includes('seamless="true"') ? "true" : "false",+ "seamless is explicit"+ );+ }+ });++ test("works inside quotes and list items but not fenced or inline code", async function (assert) {+ for (const input of [+ '> [ai-artifact share="quoted"]',+ '- [ai-artifact id="7"]',+ ]) {+ assert.strictEqual(+ artifactElements(await cookedMarkup(input)).length,+ 1,+ `${input} is parsed inside its markdown container`+ );+ }++ for (const input of [+ '`[ai-artifact id="7" autorun="true"]`',+ '```\n[ai-artifact share="key" autorun="false"]\n```',+ ' [ai-artifact id="7"]',+ '```html\n<div class="ai-artifact" data-ai-artifact-id="7" data-ai-artifact-width="600"></div>\n```',+ '- item\n\n [ai-artifact id="7"]',+ ]) {+ assert.strictEqual(+ artifactElements(await cookedMarkup(input)).length,+ 0,+ `${input} remains code`+ );+ }+ });++ test("only an entire standalone line is parsed, including adjacent blocks", async function (assert) {+ for (const input of [+ 'Before [ai-artifact id="7"]',+ '[ai-artifact id="7"] after',+ ]) {+ assert.strictEqual(+ artifactElements(await cookedMarkup(input)).length,+ 0,+ `${input} does not steal inline prose`+ );+ }++ for (const input of [+ 'Before\n[ai-artifact id="7"]\nAfter',+ '[ai-artifact id="7"]\ncontinued prose',+ '# Heading\n[ai-artifact id="7"]\n- item',+ '[ai-artifact id="7"]\n# Heading',+ '- item\n[ai-artifact id="7"]',+ 'Before\n\n[ai-artifact id="7"]\n\nAfter',+ ]) {+ const markup = await cookedMarkup(input);+ assert.strictEqual(+ artifactElements(markup).length,+ 1,+ `${input} renders a whole-line tag`+ );+ assert.true(+ markup.includes('data-ai-artifact-id="7"'),+ `${input} preserves the mount point`+ );+ }+ });++ test("invalid or ambiguous attribute syntax is inert", async function (assert) {+ const invalid = [+ "[ai-artifact]",+ '[ai-artifact version="2"]',+ '[ai-artifact share="abc" id="3"]',+ '[ai-artifact share="abc" version="2"]',+ '[ai-artifact id="3" id="4"]',+ '[ai-artifact share="abc" share="def"]',+ '[ai-artifact id="3" width="100"]',+ '[ai-artifact id="3" autorun="true" autorun="false"]',+ '[ai-artifact share="key" autorun="false" autorun="false"]',+ '[ai-artifact share="key" autorun="true" width="100"]',+ '[ai-artifact share="key" seamless="1"]',+ '[ai-artifact id="3" seamless="TRUE"]',+ '[ai-artifact id="3" seamless="true" seamless="false"]',+ '[ai-artifact id="3" height="0"]',+ '[ai-artifact id="3" height="2001"]',+ '[ai-artifact id="3" height="-1"]',+ '[ai-artifact id="3" height="1.2"]',+ '[ai-artifact id="3" height="99999999999999999999"]',+ '[ai-artifact id="3" autorun=""]',+ '[ai-artifact id="3" autorun="1"]',+ '[ai-artifact id="3" autorun="TRUE"]',+ '[ai-artifact id="3" autorun="yes"]',+ '[ai-artifact share="key" autorun="0"]',+ '[ai-artifact share="key" autorun="false "]',+ '[ai-artifact id="3" autorun=true]',+ '[ai-artifact id="3" autorun="true" bare]',+ '[ai-artifact share=""]',+ `[ai-artifact share="${"a".repeat(129)}"]`,+ '[ai-artifact share="a/b"]',+ '[ai-artifact share="https://example.com/a"]',+ '[ai-artifact share="a\" onclick=\"bad"]',+ '[ai-artifact id="0"]',+ '[ai-artifact id="-1"]',+ '[ai-artifact id="1.2"]',+ '[ai-artifact id="12345678901234567890"]',+ '[ai-artifact id="3" version="-1"]',+ '[ai-artifact id="3" version="12345678901234567890"]',+ "[ai-artifact id=3]",+ "[ai-artifact id='3']",+ ];++ for (const input of invalid) {+ const markup = await cookedMarkup(input);+ assert.strictEqual(+ artifactElements(markup).length,+ 0,+ `${input} is not an artifact`+ );+ assert.true(markup.includes("ai-artifact"), `${input} stays visible`);+ }+ });++ test("AI setting gates native syntax but not existing HTML allowlist", async function (assert) {+ const markup = await cookedMarkup('[ai-artifact id="3"]', {+ siteSettings: { discourse_ai_enabled: false },+ });+ assert.strictEqual(+ artifactElements(markup).length,+ 0,+ "disabled AI does not parse native syntax"+ );++ const legacy = await cookedMarkup(+ '<div class="ai-artifact" data-ai-artifact-id="3" data-ai-artifact-version="2" data-ai-artifact-autorun="true" data-ai-artifact-height="400" data-ai-artifact-width="600" data-ai-artifact-seamless="true"></div>',+ { siteSettings: { discourse_ai_enabled: false } }+ );+ const [artifact] = artifactElements(legacy);+ for (const [name, value] of [+ ["data-ai-artifact-id", "3"],+ ["data-ai-artifact-version", "2"],+ ["data-ai-artifact-autorun", "true"],+ ["data-ai-artifact-height", "400"],+ ["data-ai-artifact-width", "600"],+ ["data-ai-artifact-seamless", "true"],+ ]) {+ assert.strictEqual(+ artifact?.getAttribute(name),+ value,+ `legacy HTML retains ${name}`+ );+ }+ });+});