A platform for community discussion. Free, open, simple.
FEATURE: Inspect other users' AI shares (#44475)
Sam1ae8b4aa1705
diff --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.rbindex c49b19d0c4e..23258a41243 100644--- 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.rb@@ -21,13 +21,24 @@ module DiscourseAienddef index+ if params.key?(:user_id) && !params[:user_id].to_s.match?(/\A[1-9]\d{0,9}\z/)+ raise Discourse::InvalidParameters.new(:user_id)+ end+ owner = params.key?(:user_id) ? User.find_by(id: params[:user_id]) : current_user+ guardian.ensure_can_inspect_ai_shares!(owner)+ can_manage = owner.id == current_user.id+render json:- ArtifactSharesQuery.new(- user: current_user,- type: params[:type],- order: params[:order],- cursor: params[:cursor],- ).call+ ArtifactSharesQuery+ .new(+ user: owner,+ published_only: !can_manage,+ type: params[:type],+ order: params[:order],+ cursor: params[:cursor],+ )+ .call+ .merge(user_id: owner.id, can_manage: can_manage)enddef creatediff --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 98dc2a77e89..5fabd5928e2 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@@ -11,12 +11,23 @@ module DiscourseAiskip_before_action :redirect_to_login_if_required, :verify_authenticity_token, only: %i[asset]def index+ if params.key?(:user_id) && !params[:user_id].to_s.match?(/\A[1-9]\d{0,9}\z/)+ raise Discourse::InvalidParameters.new(:user_id)+ end+ owner = params.key?(:user_id) ? User.find_by(id: params[:user_id]) : current_user+ guardian.ensure_can_inspect_ai_shares!(owner)+ can_manage = owner.id == current_user.id+render json:- SharedConversationsQuery.new(- user: current_user,- order: params[:order],- cursor: params[:cursor],- ).call+ SharedConversationsQuery+ .new(+ user: owner,+ published_only: !can_manage,+ order: params[:order],+ cursor: params[:cursor],+ )+ .call+ .merge(user_id: owner.id, can_manage: can_manage)enddef creatediff --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.gjsindex 9d6d28a176c..ea4c6c05774 100644--- 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.gjs@@ -8,10 +8,14 @@ export default class AiSharingActivityTabs extends Component {@service siteSettings;get showConversations() {+ const user = this.args.outletArgs?.model;return (this.siteSettings.discourse_ai_enabled &&this.currentUser &&- this.currentUser.id === this.args.outletArgs?.model?.id+ user &&+ Number.isInteger(user.id) &&+ user.id > 0 &&+ (this.currentUser.admin || this.currentUser.id === user.id));}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.gjsindex 50df429d743..7ee3c0c9b7d 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/shared-artifacts-list.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/shared-artifacts-list.gjs@@ -37,6 +37,17 @@ export default class SharedArtifactsList extends Component {this.nextCursor = this.args.data.next_cursor;}+ willDestroy() {+ super.willDestroy(...arguments);+ if (this._revokeConfirmationOpen) {+ this.dialog.cancel();+ }+ }++ get canManage() {+ return this.args.data.can_manage === true;+ }+get canLoadMore() {return this.hasMore && !this.loadError && !this._revokeConfirmationOpen;}@@ -47,7 +58,12 @@ export default class SharedArtifactsList extends Component {@actionasync copyLink(item) {- if (this.loading || this._revokeConfirmationOpen || !item.available) {+ if (+ !this.canManage ||+ this.loading ||+ this._revokeConfirmationOpen ||+ !item.available+ ) {return;}await this.#copy(this.#absoluteURL(item.url));@@ -55,7 +71,12 @@ export default class SharedArtifactsList extends Component {@actionasync copyPostEmbed(item) {- if (this.loading || this._revokeConfirmationOpen || !item.available) {+ if (+ !this.canManage ||+ this.loading ||+ this._revokeConfirmationOpen ||+ !item.available+ ) {return;}await this.#copy(formatAiArtifactPostEmbed(item));@@ -63,7 +84,12 @@ export default class SharedArtifactsList extends Component {@actionasync copyWebsiteEmbed(item) {- if (this.loading || this._revokeConfirmationOpen || !item.available) {+ if (+ !this.canManage ||+ this.loading ||+ this._revokeConfirmationOpen ||+ !item.available+ ) {return;}const url = this.#absoluteURL(item.embed_url || item.url);@@ -74,7 +100,7 @@ export default class SharedArtifactsList extends Component {@actionrevoke(item) {- if (this.loading || this._revokeConfirmationOpen) {+ if (!this.canManage || this.loading || this._revokeConfirmationOpen) {return;}@@ -157,7 +183,7 @@ export default class SharedArtifactsList extends Component {}async #revokeConfirmed(item) {- if (this.loading) {+ if (!this.canManage || this.loading) {return;}this.loading = true;@@ -201,6 +227,7 @@ export default class SharedArtifactsList extends Component {#fetch(filter, order, cursor) {return ajax(SHARES_URL, {data: {+ user_id: this.args.data.user_id,type: filter,order,...(cursor !== null && cursor !== undefined@@ -315,44 +342,46 @@ export default class SharedArtifactsList extends Component {}}</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"- />+ {{#if this.canManage}}+ <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-default shared-artifacts__embed-website"- @action={{fn this.copyWebsiteEmbed item}}+ class="btn-danger shared-artifacts__revoke"+ @action={{fn this.revoke item}}@disabled={{this.loading}}- @icon="code"- @label="discourse_ai.ai_artifact.embed_website"- @title="discourse_ai.ai_artifact.embed_website_title"+ @icon="far-trash-can"+ @label={{if+ (eq item.type "conversation")+ "discourse_ai.ai_artifact.revoke_conversation"+ "discourse_ai.ai_artifact.revoke"+ }}/>- {{/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>+ </div>+ {{/if}}</li>{{else}}{{#unless this.hasMore}}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.gjsindex b13d1f44ccc..ff26942d11b 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/shared-conversations-list.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/shared-conversations-list.gjs@@ -35,6 +35,17 @@ export default class SharedConversationsList extends Component {this.nextCursor = this.args.data.next_cursor;}+ willDestroy() {+ super.willDestroy(...arguments);+ if (this._revokeConfirmationOpen) {+ this.dialog.cancel();+ }+ }++ get canManage() {+ return this.args.data.can_manage === true;+ }+get canLoadMore() {return this.hasMore && !this.loadError && !this._revokeConfirmationOpen;}@@ -45,7 +56,12 @@ export default class SharedConversationsList extends Component {@actionasync copyLink(item) {- if (this.loading || this._revokeConfirmationOpen || !item.available) {+ if (+ !this.canManage ||+ this.loading ||+ this._revokeConfirmationOpen ||+ !item.available+ ) {return;}const url = /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(item.url)@@ -64,7 +80,7 @@ export default class SharedConversationsList extends Component {@actionrevoke(item) {- if (this.loading || this._revokeConfirmationOpen) {+ if (!this.canManage || this.loading || this._revokeConfirmationOpen) {return;}@@ -136,7 +152,7 @@ export default class SharedConversationsList extends Component {}async #revokeConfirmed(item) {- if (this.loading) {+ if (!this.canManage || this.loading) {return;}this.loading = true;@@ -156,6 +172,7 @@ export default class SharedConversationsList extends Component {#fetch(order, cursor) {return ajax(SHARES_URL, {data: {+ user_id: this.args.data.user_id,order,...(cursor !== null && cursor !== undefined? { cursor: JSON.stringify(cursor) }@@ -217,24 +234,26 @@ export default class SharedConversationsList extends Component {}}</p>{{/unless}}</div>- <div class="shared-conversations__actions">- {{#if item.available}}+ {{#if this.canManage}}+ <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-default shared-conversations__copy-link"- @action={{fn this.copyLink item}}+ class="btn-danger shared-conversations__revoke"+ @action={{fn this.revoke item}}@disabled={{this.loading}}- @icon="link"- @label="discourse_ai.ai_artifact.copy_link"+ @icon="far-trash-can"+ @label="discourse_ai.ai_artifact.revoke_conversation"/>- {{/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>+ </div>+ {{/if}}</li>{{else}}{{#unless this.hasMore}}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.gjsindex 84275aa0293..0f42b5d430a 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-shares.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-artifact-shares.gjs@@ -3,4 +3,28 @@ import AiSharingActivityTabs from "../components/ai-sharing-activity-tabs";export default apiInitializer((api) => {api.renderInOutlet("user-activity-bottom", AiSharingActivityTabs);++ const displayed = ({ siteSettings, currentUser, user }) =>+ siteSettings.discourse_ai_enabled &&+ currentUser &&+ user &&+ Number.isInteger(user.id) &&+ user.id > 0 &&+ (currentUser.admin || currentUser.id === user.id);++ api.addUserNavSidebarLink("activity", {+ name: "activity-shared-ai-artifacts",+ route: "userActivity.sharedAiArtifacts",+ label: "discourse_ai.ai_artifact.shared_artifacts",+ icon: "code",+ displayed,+ });++ api.addUserNavSidebarLink("activity", {+ name: "activity-shared-ai-conversations",+ route: "userActivity.sharedAiConversations",+ label: "discourse_ai.shared_ai_conversations.title",+ icon: "comment",+ displayed,+ });});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.jsindex ed8b3ec4290..3413eb62671 100644--- 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.js@@ -9,17 +9,23 @@ export default class UserActivitySharedAiArtifacts extends DiscourseRoute {@service siteSettings;beforeModel() {+ const user = this.modelFor("user");if (!this.siteSettings.discourse_ai_enabled ||!this.currentUser ||- this.modelFor("user")?.id !== this.currentUser.id+ !user ||+ !Number.isInteger(user.id) ||+ user.id <= 0 ||+ (!this.currentUser.admin && user.id !== this.currentUser.id)) {return this.router.replaceWith("userActivity.index");}}model() {- return ajax("/discourse-ai/ai-bot/artifact-shares.json");+ return ajax("/discourse-ai/ai-bot/artifact-shares.json", {+ data: { user_id: this.modelFor("user").id },+ });}titleToken() {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.jsindex 00856ef73fd..a6666586a46 100644--- 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.js@@ -9,17 +9,23 @@ export default class UserActivitySharedAiConversations extends DiscourseRoute {@service siteSettings;beforeModel() {+ const user = this.modelFor("user");if (!this.siteSettings.discourse_ai_enabled ||!this.currentUser ||- this.modelFor("user")?.id !== this.currentUser.id+ !user ||+ !Number.isInteger(user.id) ||+ user.id <= 0 ||+ (!this.currentUser.admin && user.id !== this.currentUser.id)) {return this.router.replaceWith("userActivity.index");}}model() {- return ajax("/discourse-ai/ai-bot/shared-ai-conversations.json");+ return ajax("/discourse-ai/ai-bot/shared-ai-conversations.json", {+ data: { user_id: this.modelFor("user").id },+ });}titleToken() {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.gjsindex b05cf02bc26..fb7aa1f01c7 100644--- 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.gjs@@ -1,3 +1,8 @@+import { array } from "@ember/helper";import SharedArtifactsList from "../../components/shared-artifacts-list";-export default <template><SharedArtifactsList @data={{@model}} /></template>+export default <template>+ {{#each (array @model) key="@identity" as |data|}}+ <SharedArtifactsList @data={{data}} />+ {{/each}}+</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.gjsindex 6c4be650952..8952f7cc7d8 100644--- 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.gjs@@ -1,3 +1,8 @@+import { array } from "@ember/helper";import SharedConversationsList from "../../components/shared-conversations-list";-export default <template><SharedConversationsList @data={{@model}} /></template>+export default <template>+ {{#each (array @model) key="@identity" as |data|}}+ <SharedConversationsList @data={{data}} />+ {{/each}}+</template>diff --git a/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rb b/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rbindex 763b2d68424..cffa6e76f75 100644--- a/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rb+++ b/plugins/discourse-ai/lib/ai_bot/artifact_shares_query.rb@@ -5,11 +5,13 @@ module DiscourseAiclass ArtifactSharesQueryFEED_PAGE_SIZE = 20MAX_CONVERSATION_SCAN = 100+ MAX_INSPECTION_SCAN = 100FEED_TYPES = %w[all standalone conversation].freezeFEED_ORDERS = %w[newest oldest].freeze- def initialize(user:, type:, order:, cursor:)+ def initialize(user:, type:, order:, cursor:, published_only: false)@user = user+ @published_only = published_only@type = type.nil? ? "all" : type@order = order.nil? ? "newest" : order@raw_cursor = cursor@@ -45,6 +47,7 @@ module DiscourseAiitems = []conversation_scans = 0+ event_scans = 0last_event = nilloop dostreams.each do |type, stream|@@ -70,10 +73,27 @@ module DiscourseAistream = streams[type]stream[:rows].shift- items.concat(stream[:cards].fetch(event.id))+ cards = stream[:cards].fetch(event.id)+ if @published_only+ cards =+ cards+ .select { |card| card[:available] }+ .map do |card|+ card.slice(:id, :type, :name, :url, :version, :created_at, :available)+ end+ if type == "conversation"+ cards = cards.first(1)+ cards.each { |card| card[:id] = "conversation-#{event.id}" }+ end+ end+ items.concat(cards)+ event_scans += 1conversation_scans += 1 if type == "conversation"last_event = feed_position(event, type)- break if items.length >= FEED_PAGE_SIZE || conversation_scans == MAX_CONVERSATION_SCAN+ if items.length >= FEED_PAGE_SIZE || conversation_scans == MAX_CONVERSATION_SCAN ||+ (@published_only && event_scans == MAX_INSPECTION_SCAN)+ break+ endendhas_more =@@ -243,7 +263,8 @@ module DiscourseAi{id: "conversation-#{conversation.id}-#{artifact_id}",type: "conversation",- name: artifact[1],+ # Inspection labels come from the publication, never the mutable private source.+ name: @published_only ? conversation.title : artifact[1],url: conversation.url,embed_url: AiArtifact.embed_url(artifact_id, version),available:diff --git a/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rb b/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rbindex 8a068e15ea1..26c0921c745 100644--- a/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rb+++ b/plugins/discourse-ai/lib/ai_bot/shared_conversations_query.rb@@ -6,8 +6,9 @@ module DiscourseAiPAGE_SIZE = 20ORDERS = %w[newest oldest].freeze- def initialize(user:, order:, cursor:)+ def initialize(user:, order:, cursor:, published_only: false)@user = user+ @published_only = published_only@order = order.nil? ? "newest" : order@raw_cursor = cursorend@@ -37,6 +38,12 @@ module DiscourseAihas_more = rows.length > PAGE_SIZEpage = rows.first(PAGE_SIZE)items = build_items(page)+ if @published_only+ items =+ items+ .select { |item| item[:available] }+ .map { |item| item.slice(:id, :title, :url, :created_at, :available) }+ end{ items: items, has_more: has_more, next_cursor: has_more ? position(page.last) : nil }enddiff --git a/plugins/discourse-ai/lib/guardian_extensions.rb b/plugins/discourse-ai/lib/guardian_extensions.rbindex f15f39078ec..e65bcaee501 100644--- a/plugins/discourse-ai/lib/guardian_extensions.rb+++ b/plugins/discourse-ai/lib/guardian_extensions.rb@@ -114,6 +114,12 @@ module DiscourseAitrueend+ def can_inspect_ai_shares?(owner)+ return false if anonymous? || !owner++ owner.id == user.id || is_admin?+ end+def can_destroy_shared_ai_bot_conversation?(conversation)return false if anonymous?diff --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 b54a75ae5c5..fffed0055b0 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@@ -61,6 +61,8 @@ RSpec.describe DiscourseAi::AiBot::SharedAiConversationsController doexpect(response).to have_http_status(:ok)expect(response.parsed_body).to eq(+ "user_id" => user.id,+ "can_manage" => true,"items" => [{"id" => conversation.id,diff --git a/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_profile_inspection_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_profile_inspection_spec.rbnew file mode 100644index 00000000000..315fe3c0c92--- /dev/null+++ b/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_profile_inspection_spec.rb@@ -0,0 +1,398 @@+# frozen_string_literal: true++RSpec.describe "Shared AI profile inspection" do+ fab!(:owner) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }+ fab!(:group)+ fab!(:llm_model)+ fab!(:agent) { Fabricate(:ai_agent, default_llm: llm_model).tap(&:ensure_user!) }+ fab!(:topic) { Fabricate(:private_message_topic, user: owner, recipient: agent.user) }+ fab!(:source_post) { Fabricate(:post, topic: topic, user: owner) }+ fab!(:artifact) { Fabricate(:ai_artifact, post: source_post, user: owner) }++ let(:artifact_path) { "/discourse-ai/ai-bot/artifact-shares" }+ let(:conversation_path) { "/discourse-ai/ai-bot/shared-ai-conversations" }+ let(:paths) { [artifact_path, conversation_path] }+ let(:share) do+ AiArtifactShare+ .new(ai_artifact: artifact, user: owner)+ .tap { |record| record.pin!(version_number: 0) }+ end+ let(:conversation) { SharedAiConversation.share_conversation(owner, topic) }++ before do+ enable_current_plugin+ SiteSetting.ai_artifact_security = "strict"+ SiteSetting.ai_bot_enabled = true+ toggle_enabled_bots(bots: [llm_model])+ group.add(owner)+ SiteSetting.ai_bot_public_sharing_allowed_groups = group.id.to_s+ source_post.update_columns(+ cooked: "<div class='ai-artifact' data-ai-artifact-id='#{artifact.id}'></div>",+ )+ end++ it "requires login for both target feeds" do+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response).to have_http_status(:forbidden)+ end+ end++ it "refuses unrelated users and moderators on both feeds, including cursors" do+ [Fabricate(:user), Fabricate(:moderator)].each do |viewer|+ sign_in(viewer)+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id, cursor: "{}" }+ expect(response).to have_http_status(:forbidden)+ expect(response.parsed_body["items"]).to be_nil+ end+ end+ end++ it "allows explicit self targets and keeps owner management" do+ share+ conversation+ sign_in(owner)++ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response).to have_http_status(:ok)+ expect(response.parsed_body.slice("user_id", "can_manage")).to eq(+ "user_id" => owner.id,+ "can_manage" => true,+ )+ expect(response.parsed_body["items"]).to be_present+ expect(response.parsed_body["items"].first).to have_key("share_key")+ end+ end++ it "returns only published representation fields to an administrator" do+ share+ conversation+ original_name = share.name+ artifact.update!(name: "Private renamed source", html: "<p>Private unpublished revision</p>")+ private_post = Fabricate(:post, topic: topic, user: owner, raw: "Unpublished private post")+ unshared = Fabricate(:ai_artifact, post: private_post, user: owner)+ storage =+ Fabricate(+ :ai_artifact_key_value,+ ai_artifact: artifact,+ user: owner,+ value: "Private storage",+ )+ sign_in(admin)++ get "#{artifact_path}.json", params: { user_id: owner.id }+ expect(response).to have_http_status(:ok)+ expect(response.parsed_body.slice("user_id", "can_manage")).to eq(+ "user_id" => owner.id,+ "can_manage" => false,+ )+ items = response.parsed_body["items"]+ expect(items.map { |item| [item["type"], item["name"], item["url"]] }).to contain_exactly(+ ["standalone", original_name, share.url],+ ["conversation", conversation.title, conversation.url],+ )+ items.each do |item|+ expect(item.keys - %w[id type name url version created_at available]).to eq([])+ end+ expect(response.body).not_to include(+ artifact.name,+ artifact.html,+ private_post.raw,+ unshared.name,+ storage.value,+ )++ get "#{conversation_path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["items"]).to eq(+ [+ {+ "id" => conversation.id,+ "title" => conversation.title,+ "url" => conversation.url,+ "created_at" => conversation.created_at.as_json,+ "available" => true,+ },+ ],+ )+ expect(response.body).not_to include(private_post.raw, storage.value, conversation.excerpt)+ end++ it "lists a conversation publication once during inspection while preserving owner artifact cards" do+ second_artifact = Fabricate(:ai_artifact, post: source_post, user: owner)+ third_artifact = Fabricate(:ai_artifact, post: source_post, user: owner)+ artifacts = [artifact, second_artifact, third_artifact]+ source_post.update_columns(+ cooked:+ artifacts+ .map { |source| "<div class='ai-artifact' data-ai-artifact-id='#{source.id}'></div>" }+ .join,+ )+ conversation+ artifact.reload.update!(metadata: { public: false })+ sign_in(admin)++ %w[newest oldest].each do |order|+ get "#{artifact_path}.json", params: { user_id: owner.id, type: "conversation", order: order }+ expect(response).to have_http_status(:ok)+ expect(+ response.parsed_body["items"].map { |item| item.slice("id", "name", "url", "available") },+ ).to eq(+ [+ {+ "id" => "conversation-#{conversation.id}",+ "name" => conversation.title,+ "url" => conversation.url,+ "available" => true,+ },+ ],+ )+ end++ sign_in(owner)+ get "#{artifact_path}.json", params: { type: "conversation" }+ expect(+ response.parsed_body["items"].map { |item| [item["id"], item["name"], item["available"]] },+ ).to eq(+ artifacts.map do |source|+ ["conversation-#{conversation.id}-#{source.id}", source.name, source != artifact]+ end,+ )+ end++ it "preserves the existing administrator conversation DELETE API despite read-only inspection controls" do+ conversation+ sign_in(admin)+ get "#{conversation_path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["can_manage"]).to eq(false)+ expect(response.parsed_body["items"].sole["url"]).to include(conversation.share_key)++ delete "#{conversation_path}/#{conversation.share_key}.json"+ expect(response).to have_http_status(:ok)+ expect(SharedAiConversation.exists?(conversation.id)).to eq(false)+ end++ it "evaluates publication against the owner even when the administrator may publish" do+ share+ conversation+ group.remove(owner)+ group.add(admin)+ sign_in(admin)++ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["items"]).to eq([])+ end+ end++ it "excludes unavailable publications while retaining them for owner revocation" do+ share+ conversation+ source_post.trash!+ sign_in(admin)+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["items"]).to eq([])+ end++ sign_in(owner)+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["items"]).to be_present+ expect(response.parsed_body["items"].pluck("available").uniq).to eq([false])+ end+ delete "#{artifact_path}/#{share.share_key}.json"+ expect(response).to have_http_status(:no_content)+ delete "#{conversation_path}/#{conversation.share_key}.json"+ expect(response).to have_http_status(:ok)+ end++ it "excludes orphaned and disabled publications rather than using administrator source access" do+ share+ conversation+ sign_in(admin)+ SiteSetting.ai_bot_enabled = false+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["items"]).to eq([])+ end++ SiteSetting.ai_bot_enabled = true+ SiteSetting.ai_artifact_security = "disabled"+ get "#{artifact_path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["items"]).to eq([])+ SiteSetting.ai_artifact_security = "strict"+ Topic.where(id: topic.id).delete_all+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["items"]).to eq([])+ end+ end++ it "requires a valid existing target and respects the plugin enablement gate" do+ sign_in(admin)+ paths.each do |path|+ ["", "bad", "#{owner.id}suffix", "999999999999", [owner.id]].each do |target|+ get "#{path}.json", params: { user_id: target }+ expect(response).to have_http_status(:bad_request)+ end+ get "#{path}.json", params: { user_id: User.maximum(:id) + 1 }+ expect(response).to have_http_status(:forbidden)+ get "#{path}.json", params: { user_id: "9999999999" }+ expect(response).to have_http_status(:forbidden)+ end++ SiteSetting.discourse_ai_enabled = false+ paths.each do |path|+ get "#{path}.json", params: { user_id: owner.id }+ expect(response).to have_http_status(:not_found)+ end+ end++ it "keeps the target and publication boundary through artifact filtering and pagination in both directions" do+ conversation+ shares =+ 22.times.map do+ source = Fabricate(:ai_artifact, post: source_post, user: owner)+ AiArtifactShare+ .new(ai_artifact: source, user: owner)+ .tap { |record| record.pin!(version_number: 0) }+ end+ admin_source = Fabricate(:ai_artifact, user: admin)+ admin_share = AiArtifactShare.new(ai_artifact: admin_source, user: admin)+ admin_share.pin!(version_number: 0)+ sign_in(admin)++ %w[newest oldest].each do |order|+ get "#{artifact_path}.json", params: { user_id: owner.id, type: "standalone", order: order }+ page = response.parsed_body+ expect(page["items"].size).to eq(20)+ expect(page["has_more"]).to eq(true)+ urls = page["items"].pluck("url")+ get "#{artifact_path}.json",+ params: {+ user_id: owner.id,+ type: "standalone",+ order: order,+ cursor: page["next_cursor"].to_json,+ }+ expect(response).to have_http_status(:ok)+ expect(urls + response.parsed_body["items"].pluck("url")).to match_array(shares.map(&:url))+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ get "#{artifact_path}.json", params: { user_id: owner.id, type: "conversation" }+ expect(response.parsed_body["items"].pluck("url")).to eq([conversation.url])+ get "#{artifact_path}.json"+ expect(response.parsed_body["items"].pluck("url")).to eq([admin_share.url])+ end++ it "continues past empty bounded inspection pages without exposing unavailable labels" do+ shares =+ 101.times.map do |index|+ AiArtifactShare.create!(+ ai_artifact_id: artifact.id + index + 1,+ user: owner,+ name: "Orphan #{index}",+ )+ end+ sign_in(admin)+ get "#{artifact_path}.json", params: { user_id: owner.id, type: "standalone" }+ page = response.parsed_body+ expect(page["items"]).to eq([])+ expect(page["has_more"]).to eq(true)+ expect(response.body).not_to include(shares.first.name)+ get "#{artifact_path}.json",+ params: {+ user_id: owner.id,+ type: "standalone",+ cursor: page["next_cursor"].to_json,+ }+ expect(response.parsed_body["items"]).to eq([])+ expect(response.parsed_body["has_more"]).to eq(false)+ end++ it "paginates available conversation publications in both directions without changing owners" do+ snapshots =+ 22.times.map do |index|+ shared_topic = Fabricate(:private_message_topic, user: owner, recipient: agent.user)+ shared_post = Fabricate(:post, topic: shared_topic, user: owner)+ SharedAiConversation.create!(+ user: owner,+ target: shared_topic,+ title: "Published #{index}",+ llm_name: "Bot",+ excerpt: shared_post.excerpt,+ context: [{ id: shared_post.id, cooked: shared_post.cooked }],+ )+ end+ sign_in(admin)+ %w[newest oldest].each do |order|+ get "#{conversation_path}.json", params: { user_id: owner.id, order: order }+ page = response.parsed_body+ expect(page["items"].size).to eq(20)+ expect(page["can_manage"]).to eq(false)+ expect(page["has_more"]).to eq(true)+ get "#{conversation_path}.json",+ params: {+ user_id: owner.id,+ order: order,+ cursor: page["next_cursor"].to_json,+ }+ expect(response).to have_http_status(:ok)+ items = page["items"] + response.parsed_body["items"]+ expected = order == "newest" ? snapshots.reverse : snapshots+ expect(items.pluck("url")).to eq(expected.map(&:url))+ expect(items.all? { |item| item["available"] && !item.key?("share_key") }).to eq(true)+ expect(response.parsed_body["has_more"]).to eq(false)+ end+ end++ it "keeps unavailable conversation pages bounded and scoped to the inspected owner" do+ snapshots =+ 22.times.map do |index|+ SharedAiConversation.create!(+ user: owner,+ target: Fabricate(:private_message_topic, user: owner, recipient: agent.user),+ title: "Withdrawn #{index}",+ llm_name: "Bot",+ excerpt: "Withdrawn excerpt",+ context: [{ id: source_post.id, cooked: source_post.cooked }],+ )+ end+ sign_in(admin)+ %w[newest oldest].each do |order|+ get "#{conversation_path}.json", params: { user_id: owner.id, order: order }+ page = response.parsed_body+ expect(page["items"]).to eq([])+ expect(page["has_more"]).to eq(true)+ expect(response.body).not_to include(snapshots.first.title)+ get "#{conversation_path}.json",+ params: {+ user_id: owner.id,+ order: order,+ cursor: page["next_cursor"].to_json,+ }+ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["items"]).to eq([])+ expect(response.parsed_body["has_more"]).to eq(false)+ end+ end++ it "does not grant artifact update, publication or revoke powers during inspection" do+ share+ sign_in(admin)+ get "#{artifact_path}.json", params: { user_id: owner.id }+ expect(response.parsed_body["can_manage"]).to eq(false)+ put "#{artifact_path}/#{share.share_key}.json", params: { user_id: owner.id, version: 0 }+ expect(response).to have_http_status(:not_found)+ delete "#{artifact_path}/#{share.share_key}.json", params: { user_id: owner.id }+ expect(response).to have_http_status(:not_found)+ post "#{artifact_path}/#{artifact.id}.json", params: { user_id: owner.id, version: 0 }+ expect(response).to have_http_status(:not_found)+ expect(share.reload.user_id).to eq(owner.id)+ end+enddiff --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.jsindex 43638b1bc15..51af5d38c6d 100644--- 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.js@@ -1,5 +1,6 @@-import { click, currentURL, visit } from "@ember/test-helpers";+import { click, currentURL, settled, visit } from "@ember/test-helpers";import { test } from "qunit";+import userFixtures from "discourse/tests/fixtures/user-fixtures";import { acceptance } from "discourse/tests/helpers/qunit-helpers";import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";import {@@ -16,15 +17,24 @@ acceptance("AI artifact - Shared artifacts profile", function (needs) {artifactRequests = 0;conversationRequests = 0;});- needs.user();+ needs.user({ admin: false, moderator: false });needs.settings({discourse_ai_enabled: true,ai_artifact_security: "strict",});needs.pretender((server, helper) => {- server.get("/discourse-ai/ai-bot/artifact-shares.json", () => {+ server.get("/u/eviltrout.json", () => {+ const profile = userFixtures["/u/eviltrout.json"];+ return helper.response({+ ...profile,+ user: { ...profile.user, admin: false, moderator: false },+ });+ });+ server.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {artifactRequests++;return helper.response({+ user_id: Number(request.queryParams.user_id),+ can_manage: true,has_more: false,next_cursor: null,items: [@@ -54,23 +64,28 @@ acceptance("AI artifact - Shared artifacts profile", function (needs) {],});});- 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.json",+ (request) => {+ conversationRequests++;+ return helper.response({+ user_id: Number(request.queryParams.user_id),+ can_manage: true,+ 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) => {@@ -87,6 +102,53 @@ acceptance("AI artifact - Shared artifacts profile", function (needs) {);});+ test("sidebar offers AI sharing links only on the enabled self profile", async function (assert) {+ this.siteSettings.sidebar_user_navigation = true;++ const artifactsLink =+ '.user-nav-sidebar-link[href="/u/eviltrout/activity/shared-ai-artifacts"]';+ const conversationsLink =+ '.user-nav-sidebar-link[href="/u/eviltrout/activity/shared-ai-conversations"]';++ await visit("/u/eviltrout/activity");+ assert+ .dom(artifactsLink)+ .hasText("Shared AI artifacts", "artifacts appear in the sidebar");+ assert+ .dom(conversationsLink)+ .hasText(+ "Shared AI conversations",+ "conversations appear in the sidebar"+ );++ await click(artifactsLink);+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-artifacts",+ "the sidebar opens artifacts"+ );+ await click(conversationsLink);+ assert.strictEqual(+ currentURL(),+ "/u/eviltrout/activity/shared-ai-conversations",+ "the sidebar opens conversations"+ );++ await visit("/u/charlie/activity");+ assert+ .dom('.user-nav-sidebar-link[href*="shared-ai"]')+ .doesNotExist("AI sharing links are private to the current user");++ this.siteSettings.discourse_ai_enabled = false;+ await visit("/u/eviltrout/activity");+ assert+ .dom(artifactsLink)+ .doesNotExist("artifacts are hidden when AI is disabled");+ assert+ .dom(conversationsLink)+ .doesNotExist("conversations are hidden when AI is disabled");+ });+test("self profile offers actions and confirms conversation revoke", async function (assert) {await visit("/u/eviltrout/activity");assert@@ -265,7 +327,7 @@ acceptance("AI artifact - Shared artifacts profile", function (needs) {});acceptance("AI artifact - Shared artifacts scrolling", function (needs) {- needs.user();+ needs.user({ admin: false, moderator: false });needs.settings({discourse_ai_enabled: true,ai_artifact_security: "strict",@@ -274,6 +336,8 @@ acceptance("AI artifact - Shared artifacts scrolling", function (needs) {server.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {if (request.queryParams.cursor) {return helper.response({+ user_id: Number(request.queryParams.user_id),+ can_manage: true,items: [{id: "conversation-43",@@ -293,6 +357,8 @@ acceptance("AI artifact - Shared artifacts scrolling", function (needs) {});}return helper.response({+ user_id: Number(request.queryParams.user_id),+ can_manage: true,items: [{id: "standalone-first",@@ -340,15 +406,17 @@ acceptance("AI artifact - Shared AI artifacts disabled", function (needs) {needs.hooks.beforeEach(() => {requests = 0;});- needs.user();+ needs.user({ admin: false, moderator: false });needs.settings({discourse_ai_enabled: true,ai_artifact_security: "disabled",});needs.pretender((server, helper) => {- server.get("/discourse-ai/ai-bot/artifact-shares.json", () => {+ server.get("/discourse-ai/ai-bot/artifact-shares.json", (request) => {requests++;return helper.response({+ user_id: Number(request.queryParams.user_id),+ can_manage: true,items: [{id: "conversation-42",@@ -418,7 +486,7 @@ acceptance("AI artifact - Shared AI artifacts disabled", function (needs) {});acceptance("AI sharing - plugin disabled", function (needs) {- needs.user();+ needs.user({ admin: false, moderator: false });needs.settings({ discourse_ai_enabled: false });test("neither activity tab nor route is available", async function (assert) {@@ -435,7 +503,7 @@ acceptance("AI sharing - plugin disabled", function (needs) {});acceptance("AI sharing - bot disabled", function (needs) {- needs.user();+ needs.user({ admin: false, moderator: false });needs.settings({discourse_ai_enabled: true,ai_bot_enabled: false,@@ -458,3 +526,422 @@ acceptance("AI sharing - bot disabled", function (needs) {assert.dom(".user-nav__activity-shared-conversations").exists();});});++acceptance("AI sharing - Administrator inspection", function (needs) {+ const requests = [];+ const state = { failNextPage: false, emptyPages: false, refreshed: false };+ needs.user({ admin: true });+ needs.settings({+ discourse_ai_enabled: true,+ ai_artifact_security: "strict",+ });+ needs.hooks.beforeEach(() => {+ requests.length = 0;+ state.failNextPage = false;+ state.emptyPages = false;+ state.refreshed = false;+ });+ needs.pretender((server, helper) => {+ for (const [username, id] of [+ ["system", -1],+ ["inspectionbot", -100],+ ["zerobot", 0],+ ]) {+ server.get(`/u/${username}.json`, () => {+ const profile = userFixtures["/u/charlie.json"];+ return helper.response({+ ...profile,+ user: { ...profile.user, username, id },+ });+ });+ }++ for (const feed of ["artifact-shares", "shared-ai-conversations"]) {+ server.get(`/discourse-ai/ai-bot/${feed}.json`, (request) => {+ const params = request.queryParams;+ requests.push({ feed, ...params });+ if (params.cursor && state.failNextPage) {+ state.failNextPage = false;+ return helper.response(500, { errors: ["Unavailable"] });+ }+ const inspected = params.user_id === "5";+ const title = state.refreshed+ ? "Fresh publication"+ : inspected+ ? "Published by Charlie"+ : "My own publication";+ if (state.emptyPages) {+ const position = params.cursor ? JSON.parse(params.cursor).id : null;+ const finished = position === 124;+ return helper.response({+ user_id: Number(params.user_id),+ can_manage: false,+ items: finished+ ? [+ {+ id: "found",+ type: "standalone",+ name: title,+ title,+ url: "/published",+ available: true,+ },+ ]+ : [],+ has_more: !finished,+ next_cursor: finished+ ? null+ : { id: position === null ? 123 : 124 },+ });+ }+ return helper.response({+ user_id: Number(params.user_id),+ can_manage: !inspected && !state.refreshed,+ items: [+ {+ id: params.cursor ? "second" : "first",+ type: "standalone",+ name: title,+ title,+ url: "/discourse-ai/ai-bot/artifact-shares/published",+ available: true,+ share_key: inspected ? undefined : "own-key",+ },+ ],+ has_more: !params.cursor && !state.refreshed,+ next_cursor:+ params.cursor || state.refreshed+ ? null+ : { id: 123, created_at: "published" },+ });+ });+ }+ });++ test("system and nonpositive bot profiles have no sidebar links, tabs or direct feeds", async function (assert) {+ for (const username of ["system", "inspectionbot", "zerobot"]) {+ this.siteSettings.sidebar_user_navigation = true;+ await visit(`/u/${username}/activity`);+ assert+ .dom('.user-nav-sidebar-link[href*="shared-ai"]')+ .doesNotExist("nonpositive targets have no sidebar inspection links");+ this.siteSettings.sidebar_user_navigation = false;+ await visit(`/u/${username}/activity`);+ assert+ .dom(".user-nav__activity-shared-artifacts")+ .doesNotExist("nonpositive targets have no artifact tab");+ assert+ .dom(".user-nav__activity-shared-conversations")+ .doesNotExist("nonpositive targets have no conversation tab");+ for (const route of [+ "shared-ai-artifacts",+ "shared-ai-conversations",+ "shared-artifacts",+ ]) {+ await visit(`/u/${username}/activity/${route}`);+ assert.strictEqual(+ currentURL(),+ `/u/${username}/activity`,+ "nonpositive targets redirect to their activity page"+ );+ }+ }+ assert.strictEqual(+ requests.length,+ 0,+ "invalid profile navigation never requests a feed or falls back to self"+ );+ });++ test("legacy tabs and canonical or legacy routes allow read-only inspection", async function (assert) {+ await visit("/u/charlie/activity");+ assert+ .dom(".user-nav__activity-shared-artifacts a")+ .exists("admin sees the artifact tab");+ assert+ .dom(".user-nav__activity-shared-conversations a")+ .exists("admin sees the conversation tab");+ await click(".user-nav__activity-shared-artifacts a");+ assert+ .dom(".shared-artifacts__card h3")+ .hasText("Published by Charlie", "published artifact is listed");+ assert+ .dom(".shared-artifacts__actions")+ .doesNotExist("inspection has no management or embed controls");+ assert+ .dom(".shared-artifacts iframe")+ .doesNotExist("inspection does not mount a mutable runtime");+ assert.deepEqual(+ requests[0],+ { feed: "artifact-shares", user_id: "5" },+ "initial request targets the inspected user"+ );++ await click(".user-nav__activity-shared-conversations a");+ assert+ .dom(".shared-conversations__card h3")+ .hasText("Published by Charlie", "conversation publication is listed");+ assert+ .dom(".shared-conversations__actions")+ .doesNotExist("conversation inspection has no revoke controls");+ assert.deepEqual(+ requests.at(-1),+ { feed: "shared-ai-conversations", user_id: "5" },+ "conversation request targets the inspected user"+ );++ await visit("/u/charlie/activity/shared-artifacts");+ assert.strictEqual(+ currentURL(),+ "/u/charlie/activity/shared-ai-artifacts",+ "legacy route resolves to the inspected feed"+ );+ });++ test("sidebar supports inspection and changing profile resets the list and owner controls", async function (assert) {+ this.siteSettings.sidebar_user_navigation = true;+ await visit("/u/charlie/activity");+ const artifactLink =+ '.user-nav-sidebar-link[href="/u/charlie/activity/shared-ai-artifacts"]';+ const conversationLink =+ '.user-nav-sidebar-link[href="/u/charlie/activity/shared-ai-conversations"]';+ assert.dom(artifactLink).exists("admin sidebar offers artifacts");+ assert.dom(conversationLink).exists("admin sidebar offers conversations");+ await click(artifactLink);+ assert+ .dom(".shared-artifacts__actions")+ .doesNotExist("inspected artifacts are read-only");++ await visit("/u/eviltrout/activity/shared-ai-artifacts");+ assert+ .dom(".shared-artifacts__card h3")+ .hasText("My own publication", "profile change replaces inspection data");+ assert+ .dom(".shared-artifacts__revoke")+ .exists("admin retains owner management on self");+ await visit("/u/charlie/activity/shared-ai-artifacts");+ assert+ .dom(".shared-artifacts__card h3")+ .hasText(+ "Published by Charlie",+ "changing back recreates inspection data"+ );+ assert+ .dom(".shared-artifacts__actions")+ .doesNotExist("owner controls cannot persist on inspection");++ this.siteSettings.discourse_ai_enabled = false;+ await visit("/u/charlie/activity");+ assert+ .dom(artifactLink)+ .doesNotExist("disabled AI hides administrator artifact navigation");+ assert+ .dom(conversationLink)+ .doesNotExist("disabled AI hides administrator conversation navigation");+ await visit("/u/charlie/activity/shared-ai-artifacts");+ assert.notStrictEqual(+ currentURL(),+ "/u/charlie/activity/shared-ai-artifacts",+ "disabled AI guards direct inspection"+ );+ });++ for (const kind of ["artifacts", "conversations"]) {+ test(`${kind} observer continues through empty inspection pages`, async function (assert) {+ state.emptyPages = true;+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ try {+ await visit(`/u/charlie/activity/shared-ai-${kind}`);+ assert+ .dom(`.shared-${kind}__card`)+ .doesNotExist("an empty first page exposes no unavailable content");+ assert+ .dom(`.shared-${kind}__empty`)+ .doesNotExist(+ "a continuation cursor suppresses the final empty state"+ );+ const firstObserver = observations.at(-1);+ await firstObserver.trigger();+ assert+ .dom(`.shared-${kind}__card`)+ .doesNotExist(+ "an empty intermediate page still exposes no unavailable content"+ );+ assert.notStrictEqual(+ observations.at(-1),+ firstObserver,+ "the observer is rearmed after the empty page"+ );+ await observations.at(-1).trigger();+ assert+ .dom(`.shared-${kind}__card h3`)+ .hasText(+ "Published by Charlie",+ "the next intersection finds the publication"+ );+ assert+ .dom(`.shared-${kind}__actions`)+ .doesNotExist("continued inspection remains read-only");+ assert.deepEqual(+ requests.map(({ user_id, cursor }) => ({ user_id, cursor })),+ [+ { user_id: "5", cursor: undefined },+ { user_id: "5", cursor: JSON.stringify({ id: 123 }) },+ { user_id: "5", cursor: JSON.stringify({ id: 124 }) },+ ],+ "empty pages advance the cursor without losing the target"+ );+ } finally {+ disableLoadMoreObserver();+ }+ });++ test(`${kind} same-user route refresh replaces data, pagination and management authorization`, async function (assert) {+ await visit(`/u/eviltrout/activity/shared-ai-${kind}`);+ assert+ .dom(`.shared-${kind}__card h3`)+ .hasText("My own publication", "the initial owner data is shown");+ assert+ .dom(`.shared-${kind}__revoke`)+ .exists("the initial response permits owner management");+ await click(`.shared-${kind}__sort`);+ await click(`.shared-${kind}__revoke`);+ assert+ .dom(".dialog-container")+ .exists("owner management confirmation is open before refresh");+ state.refreshed = true;+ await this.owner+ .lookup(`route:user-activity.shared-ai-${kind}`)+ .refresh();+ await settled();++ assert+ .dom(`.shared-${kind}__card h3`)+ .hasText(+ "Fresh publication",+ "a refreshed response replaces the same user's old data"+ );+ assert+ .dom(`.shared-${kind}__actions`)+ .doesNotExist(+ "the refreshed management authorization replaces old controls"+ );+ assert+ .dom(".dialog-container")+ .doesNotExist(+ "refresh dismisses the stale owner management confirmation"+ );+ assert+ .dom(`.shared-${kind}__sort`)+ .hasText("Newest first", "refresh resets the prior sort state");+ assert.strictEqual(+ requests.at(-1).user_id,+ "19",+ "refresh still explicitly requests the same target"+ );+ });++ test(`${kind} sort, pagination and retries retain the inspected target`, async function (assert) {+ enableLoadMoreObserver();+ const observations = stubIntersectionObserver();+ try {+ await visit(`/u/charlie/activity/shared-ai-${kind}`);+ if (kind === "artifacts") {+ await click(".shared-artifacts__filters button:nth-child(2)");+ }+ assert.strictEqual(+ requests.at(-1).type,+ kind === "artifacts" ? "standalone" : undefined,+ "only the artifact feed carries its selected filter"+ );+ await click(`.shared-${kind}__sort`);+ assert.strictEqual(+ requests.at(-1).order,+ "oldest",+ "sorting is passed to the target feed"+ );+ state.failNextPage = true;+ await observations.at(-1).trigger();+ assert+ .dom(`.shared-${kind}__retry`)+ .exists("failed target pagination offers retry");+ const failedRequest = requests.at(-1);+ await click(`.shared-${kind}__retry`);+ assert.deepEqual(+ requests.at(-1),+ failedRequest,+ "retry retains the target, order, filter and cursor"+ );+ assert+ .dom(`.shared-${kind}__card`)+ .exists({ count: 2 }, "target page is appended");+ assert.true(+ requests.every((request) => request.user_id === "5"),+ "every request explicitly targets Charlie"+ );+ assert+ .dom(`.shared-${kind}__actions`)+ .doesNotExist("pagination does not introduce management controls");+ } finally {+ disableLoadMoreObserver();+ }+ });+ }+});++for (const viewer of ["moderator", "anonymous"]) {+ acceptance(`AI sharing - ${viewer} access`, function (needs) {+ const state = { requests: 0 };+ if (viewer === "moderator") {+ needs.user({ moderator: true, admin: false });+ }+ needs.settings({+ discourse_ai_enabled: true,+ sidebar_user_navigation: true,+ });+ needs.hooks.beforeEach(() => {+ state.requests = 0;+ });+ needs.pretender((server, helper) => {+ for (const feed of ["artifact-shares", "shared-ai-conversations"]) {+ server.get(`/discourse-ai/ai-bot/${feed}.json`, () => {+ state.requests++;+ return helper.response({ items: [], has_more: false });+ });+ }+ });++ test("another user's sidebar and direct feeds are inaccessible", async function (assert) {+ await visit("/u/charlie/activity");+ assert+ .dom('.user-nav-sidebar-link[href*="shared-ai"]')+ .doesNotExist("inspection links are hidden");+ this.siteSettings.sidebar_user_navigation = false;+ await visit("/u/charlie/activity");+ assert+ .dom(".user-nav__activity-shared-artifacts")+ .doesNotExist("artifact tab is hidden");+ assert+ .dom(".user-nav__activity-shared-conversations")+ .doesNotExist("conversation tab is hidden");+ for (const route of [+ "shared-ai-artifacts",+ "shared-ai-conversations",+ "shared-artifacts",+ ]) {+ await visit(`/u/charlie/activity/${route}`);+ assert.notStrictEqual(+ currentURL(),+ `/u/charlie/activity/${route}`,+ "direct feed navigation redirects away"+ );+ }+ assert.strictEqual(+ state.requests,+ 0,+ "guarded navigation makes no feed requests"+ );+ });+ });+}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.gjsindex a4a8f20cf9f..9825a50433c 100644--- 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.gjs@@ -14,7 +14,12 @@ 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 };+ return {+ items,+ has_more: hasMore,+ next_cursor: nextCursor,+ can_manage: true,+ };}function share(name, shareKey, available = true) {@@ -841,4 +846,37 @@ module("Integration | Component | SharedArtifactsList", function (hooks) {assert.dom(".shared-artifacts__retry").doesNotExist("retry clears");assert.dom(".shared-artifacts__card").exists({ count: 2 }, "page appended");});++ test("inspection renders published links without management controls", async function (assert) {+ this.data = {+ ...listData([share("Published", "published")]),+ user_id: 5,+ can_manage: false,+ };+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ assert+ .dom(".shared-artifacts__card h3 a")+ .exists("published representation remains accessible");+ assert+ .dom(".shared-artifacts__actions")+ .doesNotExist("inspection renders no management, copy or embed controls");+ assert+ .dom("iframe")+ .doesNotExist("inspection never mounts an artifact runtime");+ });++ test("missing management authorization hides owner controls", async function (assert) {+ this.data = listData([share("Published", "published")]);+ delete this.data.can_manage;+ await render(+ <template><SharedArtifactsList @data={{this.data}} /></template>+ );++ assert+ .dom(".shared-artifacts__actions")+ .doesNotExist("management defaults to denied");+ });});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.gjsindex 4f2d4fafdb8..e331096b588 100644--- 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.gjs@@ -14,7 +14,12 @@ 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 };+ return {+ items,+ has_more: hasMore,+ next_cursor: nextCursor,+ can_manage: true,+ };}function share(id, available = true) {@@ -231,4 +236,33 @@ module("Integration | Component | SharedConversationsList", function (hooks) {await Promise.all([firstLoad, secondLoad]);assert.dom(".shared-conversations__card h3").hasText("Conversation 2");});++ test("inspection renders published links without management controls", async function (assert) {+ this.data = { ...listData([share(1)]), user_id: 5, can_manage: false };+ await render(+ <template><SharedConversationsList @data={{this.data}} /></template>+ );++ assert+ .dom(".shared-conversations__card h3 a")+ .exists("published representation remains accessible");+ assert+ .dom(".shared-conversations__actions")+ .doesNotExist("inspection renders no management, copy or embed controls");+ assert+ .dom("iframe")+ .doesNotExist("inspection never mounts an artifact runtime");+ });++ test("missing management authorization hides owner controls", async function (assert) {+ this.data = listData([share(1)]);+ delete this.data.can_manage;+ await render(+ <template><SharedConversationsList @data={{this.data}} /></template>+ );++ assert+ .dom(".shared-conversations__actions")+ .doesNotExist("management defaults to denied");+ });});diff --git a/plugins/discourse-ai/test/javascripts/unit/routes/user-activity-ai-share-guards-test.js b/plugins/discourse-ai/test/javascripts/unit/routes/user-activity-ai-share-guards-test.jsnew file mode 100644index 00000000000..d758cc5361a--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/unit/routes/user-activity-ai-share-guards-test.js@@ -0,0 +1,48 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";++module("Unit | Route | user-activity AI share guards", function (hooks) {+ setupTest(hooks);+ hooks.afterEach(() => sinon.restore());++ test("administrators are redirected when the target model is missing or invalid", function (assert) {+ const router = this.owner.lookup("service:router");+ const redirect = {};+ const replaceWith = sinon.stub(router, "replaceWith").returns(redirect);+ const targets = [+ undefined,+ null,+ {},+ { id: 0 },+ { id: -1 },+ { id: -100 },+ { id: "5" },+ ];++ for (const name of [+ "shared-ai-artifacts",+ "shared-ai-conversations",+ "shared-artifacts",+ ]) {+ const route = this.owner.lookup(`route:user-activity.${name}`);+ route.set("currentUser", { id: 19, admin: true });+ route.set("siteSettings", { discourse_ai_enabled: true });+ const modelFor = sinon.stub(route, "modelFor");++ for (const target of targets) {+ modelFor.returns(target);+ replaceWith.resetHistory();+ assert.strictEqual(+ route.beforeModel(),+ redirect,+ `${name} rejects a missing or nonpositive target`+ );+ assert.true(+ replaceWith.calledOnceWithExactly("userActivity.index"),+ `${name} redirects to activity, never the self feed`+ );+ }+ }+ });+});