Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.
Ruby agplai-assistantdockerdsgvogdprhotwireissue-trackerjira-alternativeknowledge-basellmmcp-servermeeting-notesopen-sourceproject-managementredmine-alternativeruby-on-railsself-hostedticketingtime-tracking
Add the REST ticket view: statuses, pages, one comment, ticket by number
Guido Boyke14fb8dae1789
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.ymlindex e813e4f..ee9da43 100644--- a/.github/workflows/guards.yml+++ b/.github/workflows/guards.yml@@ -291,6 +291,7 @@ jobs:spec/requests/api/v1/error_codes_spec.rbspec/requests/api/v1/idempotency_spec.rbspec/requests/api/v1/capabilities_spec.rb+ spec/requests/api/v1/ticket_view_spec.rbspec/models/codebase_import_mapping_spec.rbspec/services/codebase_import/time_session_importer_spec.rbspec/services/codebase_import/duplicate_prevention_spec.rbdiff --git a/CLAUDE.md b/CLAUDE.mdindex 39f3085..58081e0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -775,7 +775,8 @@ Drei Namensräume unter `/api`, und sie unterscheiden sich darin, **wer** ruft:* Antworten tragen **eine** Hülle: `data.<ding>` im Erfolg, `error.{code,messages}` im Fehler.`code` ist maschinenlesbar, `messages` sind übersetzter Text.-For the seven REST ticket member routes, `Api::V1::ReadableTicket` resolves tickets+For the REST ticket member routes (including `GET /tickets/:ticket_id/posts/:id`) and the+number route, `Api::V1::ReadableTicket` resolves ticketsthrough the token's effective organisation/project reach and `TicketPolicy::Scope`:missing and unreadable tickets return 404 with `{"error":"not_found","code":"not_found"}`.Denied actions on readable tickets remain 403; read-only tokens reject writes with 403@@ -809,6 +810,24 @@ feature by feature):pinned against the routes both ways (`spec/requests/api/v1/capabilities_spec.rb`): a newendpoint adds its line there. Additive changes bump the minor.+**Ticket view** (REST R1, 2026-10-29, API 1.2.0):++* `GET /projects/:project_id/tickets` names `meta.available_statuses`, the project's status+ keys from the same source as MCP `list_tickets`.+* `GET /tickets/:id` takes opt-in pages: any one of `posts_page`, `posts_per_page` (at most+ 50, above is 422), `posts_order` (`oldest`, `newest`), `attachments_page` (10 per page)+ switches the answer to the paged fields of MCP `get_ticket` (`posts_total`,+ `posts_truncated`, `attachments`, ...). **Without them the body stays byte-equal** (the+ contract records it; gboyke/lalabase-mcp reads it). Invalid values: 422 `invalid_input`,+ checked before the ticket is looked up. REST does not truncate bodies.+* `GET /projects/:project_id/tickets/number/:number` answers what `GET /tickets/:id` answers,+ paging included. Missing, malformed (`abc`, `0`), unreadable, out of reach or foreign: the+ same 404. The number is looked up only inside that project.+* `GET /tickets/:ticket_id/posts/:id`: one readable comment, whole, in the shape of a comment+ in the ticket. Hidden private, foreign and missing comments: the same 404.+* Options and pages come from `Tickets::Reading`, shared with MCP `get_ticket`; MCP keeps its+ caps. Guard: `spec/requests/api/v1/ticket_view_spec.rb`.+`GET /api/v1/time_sessions/open` lists the person's own open hours within the token'sreach, organisations AND projects, and only the rows the web time list shows them(`TimeSessions::ViewingScope`). A booking on a ticket they cannot read keeps its row anddiff --git a/app/controllers/api/v1/posts_controller.rb b/app/controllers/api/v1/posts_controller.rbindex 2a51bba..93ce634 100644--- a/app/controllers/api/v1/posts_controller.rb+++ b/app/controllers/api/v1/posts_controller.rb@@ -26,6 +26,22 @@ module Apiendend+ # GET /api/v1/tickets/:ticket_id/posts/:id+ #+ # One comment, whole, in the shape the ticket view lists it. Out of the+ # reader's readable comments of THIS ticket (Tickets::Reading#post): a+ # hidden private comment, a comment of another ticket and a missing one+ # answer the same 404 as an unreadable ticket.+ def show+ with_readable_ticket(params[:ticket_id]) do |ticket|+ post = Tickets::Reading.new(serializer: Tickets::Serializer.new(current_user: current_user))+ .post(ticket, params[:id])+ raise ActiveRecord::RecordNotFound if post.nil?++ render json: { data: post }+ end+ end+privatedef post_attributesdiff --git a/app/controllers/api/v1/tickets_controller.rb b/app/controllers/api/v1/tickets_controller.rbindex 8fd108d..694cd14 100644--- a/app/controllers/api/v1/tickets_controller.rb+++ b/app/controllers/api/v1/tickets_controller.rb@@ -7,6 +7,12 @@ module Apiidempotent :create, :update+ # Raised while the paging options are read, before any ticket is looked+ # up: the 422 does not depend on whether the ticket exists.+ rescue_from Tickets::Reading::InvalidOption, with: :invalid_paging++ SHOW_PRELOAD = %i[creator assignees].freeze+MAX_PER_PAGE = 100DEFAULT_PER_PAGE = 25@@ -35,7 +41,11 @@ module Apirender json: {data: filter.paginate(scope).map { |t| ticket_serializer.summary(t) },- meta: { page: filter.page, per_page: filter.per_page, total: filter.total(scope) }+ # available_statuses: the project's status keys, the source MCP+ # list_tickets names them from (REST R1), so a client filters by a+ # status the project actually has.+ meta: { page: filter.page, per_page: filter.per_page, total: filter.total(scope),+ available_statuses: TicketAttributeDefinition.ordered_value_keys_for(project, 'status') }}endend@@ -65,12 +75,20 @@ module Apiendend+ # Without paging parameters the body is what it always was (every readable+ # comment, no attachments); gboyke/lalabase-mcp reads it. Any one of them+ # switches to pages (REST R1).def show- with_readable_ticket(params[:id], preload: %i[creator assignees]) do |ticket|- render json: {- data: ticket_serializer.full(ticket),- permissions: serialize_permissions(ticket)- }+ paging = paging_options+ with_readable_ticket(params[:id], preload: SHOW_PRELOAD) { |ticket| render_ticket(ticket, paging) }+ end++ # GET /api/v1/projects/:project_id/tickets/number/:number+ # The same answer as #show for the ticket of that number in that project.+ def by_number+ paging = paging_options+ with_readable_ticket_number(params[:project_id], params[:number], preload: SHOW_PRELOAD) do |ticket|+ render_ticket(ticket, paging)endend@@ -118,6 +136,35 @@ module Apiprivate+ def render_ticket(ticket, paging)+ render json: { data: ticket_data(ticket, paging), permissions: serialize_permissions(ticket) }+ end++ # The pages come from Tickets::Reading, shared with MCP get_ticket, without+ # its caps: REST hands descriptions and comments out whole.+ def ticket_data(ticket, paging)+ return ticket_serializer.full(ticket) if paging.nil?++ reading = Tickets::Reading.new(serializer: ticket_serializer)+ ticket_serializer.full(ticket, posts: false)+ .merge(reading.post_page(ticket, paging))+ .merge(reading.attachment_page(ticket, paging.attachments_page))+ end++ # nil without any paging parameter. Above 50 comments per page REST refuses+ # where MCP clamps.+ def paging_options+ return nil unless Tickets::Reading.paging_requested?(params)++ args = Tickets::Reading::PAGING_KEYS.to_h { |key| [key.to_sym, params[key]] }+ Tickets::Reading.options(args, over_max: :refuse)+ end++ def invalid_paging(exception)+ render_error(error: 'invalid_input', code: 'invalid_input', message: exception.message,+ status: :unprocessable_content)+ end+# Renders an actor failure Result. The machine-readable code becomes both# the `error` field and (via ACTOR_ERROR_STATUS) the HTTP status, so a# client can distinguish validation (422) from a conflict (409) etc.;diff --git a/app/controllers/concerns/api/v1/readable_ticket.rb b/app/controllers/concerns/api/v1/readable_ticket.rbindex 4c02c10..706edc8 100644--- a/app/controllers/concerns/api/v1/readable_ticket.rb+++ b/app/controllers/concerns/api/v1/readable_ticket.rb@@ -2,31 +2,54 @@module Apimodule V1- # One read gate for the seven REST ticket member routes. Missing, out-of-reach- # and unreadable tickets return the same 404 body; readable tickets still- # require the action's write permission. Token write refusal runs before this.+ # One read gate for the REST ticket member routes and the ticket number route.+ # Missing, out-of-reach and unreadable tickets return the same 404 body;+ # readable tickets still require the action's write permission. Token write+ # refusal runs before this.## The tenant is initially unknown, so discovery reads only organisation_id and# project_id without a tenant. Query counts deliberately differ for missing# and hidden tickets: IDs are random UUIDs, not sequential ticket numbers. The# contract is equal status and body, not equal queries or constant timing.+ #+ # By number (REST R1): the project is discovered the same way, then the+ # number is looked up inside THAT project only, through the same reach check+ # and policy scope. A number is unique per project, so a number never+ # resolves to a sibling project's ticket. Because numbers ARE sequential,+ # status and body are what must not tell an unknown number from a hidden one:+ # both end in the same RecordNotFound.module ReadableTicketextend ActiveSupport::Concernprivate- def with_readable_ticket(id, preload: [])+ def with_readable_ticket(id, preload: [], &)raise ActiveRecord::RecordNotFound if id.blank?address = ActsAsTenant.without_tenant { Ticket.where(id: id).pick(:organisation_id, :project_id) }+ read_ticket(address, { id: id }, preload, &)+ end++ # A malformed number ("abc", "0") is a missing address, not an invalid+ # argument: 404 like a UUID that names nothing.+ def with_readable_ticket_number(project_id, raw_number, preload: [], &)+ number = Lalabase::Tools::TicketNumber.parse(raw_number)+ raise ActiveRecord::RecordNotFound if project_id.blank? || number.nil?++ # The stored id, not the parameter: the reach compares ids as strings.+ address = ActsAsTenant.without_tenant { Project.where(id: project_id).pick(:organisation_id, :id) }+ read_ticket(address, { number: number }, preload, &)+ end++ def read_ticket(address, conditions, preload)raise ActiveRecord::RecordNotFound unless addressorganisation_id, project_id = addressraise ActiveRecord::RecordNotFound unless current_token.reach.project_id?(organisation_id, project_id)ActsAsTenant.with_tenant(Organisation.find(organisation_id)) do- relation = Ticket.where(organisation_id: organisation_id, project_id: project_id)- ticket = Pundit.policy_scope!(current_user, relation).includes(:project, *preload).find(id)+ relation = Ticket.where(organisation_id: organisation_id, project_id: project_id).where(conditions)+ ticket = Pundit.policy_scope!(current_user, relation).includes(:project, *preload).take!raise ActiveRecord::RecordNotFound unless ticket.projectauthorize ticket, :show?diff --git a/app/services/api/v1/capabilities.rb b/app/services/api/v1/capabilities.rbindex 3663649..67c9e6c 100644--- a/app/services/api/v1/capabilities.rb+++ b/app/services/api/v1/capabilities.rb@@ -15,7 +15,7 @@ module Apimodule Capabilities# Minor for an additive change (a new endpoint, field or capability), major# never: an existing name, field or meaning does not change.- API_VERSION = '1.1.0'+ API_VERSION = '1.2.0'# name => [verb, path as the router spells it]ENDPOINTS = {@@ -25,11 +25,13 @@ module Api'projects.ticket_attribute_definitions' => ['GET', '/api/v1/projects/:id/ticket_attribute_definitions'],'tickets.list' => ['GET', '/api/v1/projects/:project_id/tickets'],'tickets.create' => ['POST', '/api/v1/projects/:project_id/tickets'],+ 'tickets.by_number' => ['GET', '/api/v1/projects/:project_id/tickets/number/:number'],'tickets.show' => ['GET', '/api/v1/tickets/:id'],'tickets.update' => ['PATCH', '/api/v1/tickets/:id'],'tickets.activities' => ['GET', '/api/v1/tickets/:id/activities'],'tickets.attachments' => ['GET', '/api/v1/tickets/:id/attachments'],'posts.create' => ['POST', '/api/v1/tickets/:ticket_id/posts'],+ 'posts.show' => ['GET', '/api/v1/tickets/:ticket_id/posts/:id'],'time_sessions.list' => ['GET', '/api/v1/tickets/:ticket_id/time_sessions'],'time_sessions.create' => ['POST', '/api/v1/tickets/:ticket_id/time_sessions'],'time_sessions.open' => ['GET', '/api/v1/time_sessions/open'],@@ -40,8 +42,10 @@ module Api}.freeze# Abilities that are not one endpoint: `idempotency` (the Idempotency-Key- # header on every write, D7) and `error_codes` (`code` on every error body, D6).- FEATURES = %w[idempotency error_codes].freeze+ # header on every write, D7), `error_codes` (`code` on every error body, D6)+ # and `tickets.paging` (the opt-in pages of comments and attachments on+ # tickets.show and tickets.by_number, R1).+ FEATURES = %w[idempotency error_codes tickets.paging].freezedef self.names(ENDPOINTS.keys + FEATURES).sortdiff --git a/app/services/lalabase/CLAUDE.md b/app/services/lalabase/CLAUDE.mdindex 08929c4..891fbf7 100644--- a/app/services/lalabase/CLAUDE.md+++ b/app/services/lalabase/CLAUDE.md@@ -1,4 +1,4 @@-# Karte: app/services/lalabase (Stand: 2026-10-28)+# Karte: app/services/lalabase (Stand: 2026-10-29)AI/RAG-Domäne (Produktname „Lalabase"): alles rund um LLM-Aufrufe, Embeddings undCodebase-Verständnis.@@ -74,6 +74,13 @@ Codebase-Verständnis.`accessible_project_ids`) ADDITIV zu `project` (R-M5, MCP unberührt), `Result#coverage`ist das L7-Deckungs-Vertragsfeld, mehrdeutige Ticketnummern antworten mit der geteiltenKandidatenliste (`tools/ticket_candidates.rb`, §9.2).+ `get_ticket` liest Seiten-Optionen und baut Kommentar-, Anhang- und Einzelseiten über+ `Tickets::Reading` (`app/services/tickets/reading.rb`, REST R1), denselben Service wie die+ REST-Ticketansicht. Im Werkzeug bleiben nur die MCP-Eigenheiten: Kappungen+ (`MAX_BODY_CHARS`, `MAX_FULL_TEXT_CHARS`, `MAX_ATTACHMENT_TEXT_CHARS`, Assistenten-Grenze),+ `full_text`, `post_id`, Zitationen. `posts_per_page` über 50 klemmt MCP auf 50+ (`over_max: :clamp`), REST lehnt mit 422 ab. Eine neue Seiten-Regel gehört in den Service,+ nicht in eine der beiden Hüllen.Fehler eines Werkzeugs tragen eine Klasse: `Result.invalid_input(msg)` oder`Result.refused(msg, reason:)`; ohne Code gilt `refused`, auch für ein abgelehntes Speichern(Modellvalidierung, Actor-Fehler): das beweist keine falsche Eingabe. Spec je Fehlerstelle:diff --git a/app/services/lalabase/tools/get_ticket.rb b/app/services/lalabase/tools/get_ticket.rbindex d65c89d..c883a96 100644--- a/app/services/lalabase/tools/get_ticket.rb+++ b/app/services/lalabase/tools/get_ticket.rb@@ -23,8 +23,12 @@ module Lalabase# bounded, and so are the attachments in both directions (how many, and how much# text each). Signed attachment download URLs are deliberately NOT included (the# serializer omits them); use the HTTP API when a real download URL is needed.+ #+ # Options and pages come from Tickets::Reading, shared with the REST ticket+ # view (cli_rest_plan D5); only the caps, full_text, post_id and the+ # citations are this tool's own.class GetTicket < Base- MAX_POSTS = 50+ MAX_POSTS = Tickets::Reading::MAX_POSTSMAX_BODY_CHARS = 8_000# MCP keeps the terminal client's full-text allowance (S1 c). The assistant# gets a smaller prefix for full_text and post_id, selected by its chat@@ -32,17 +36,14 @@ module Lalabase# allowance; Base.cap_text adds the truncation marker outside that allowance.MAX_FULL_TEXT_CHARS = 100_000MAX_ASSISTANT_FULL_TEXT_CHARS = 16_000- # Far beyond any real ticket, close enough to keep the OFFSET in range- # (the same reasoning as Notifications::InboxQuery::MAX_PAGE).- MAX_PAGE = 100_000- POST_ORDERS = %w[oldest newest].freeze+ MAX_PAGE = Tickets::Reading::MAX_PAGE+ POST_ORDERS = Tickets::Reading::POST_ORDERS- # The paging and full-text arguments, parsed once, refused when unusable+ # The paging arguments (Tickets::Reading.options) plus this tool's own+ # full_text and post_id, parsed once, refused when unusable# (Notifications::InboxQuery's rule: no silent default for a value that# cannot be read).- Options = Struct.new(:posts_page, :posts_per_page, :newest, :attachments_page, :full_text, :post_id,- keyword_init: true)- class InvalidOption < ArgumentError; end+ Options = Struct.new(:paging, :full_text, :post_id, keyword_init: true)# Attachments are bounded twice: how MANY files answer, and how much text each# one contributes.@@ -56,7 +57,7 @@ module Lalabase# characters, plus markers and JSON. This does not guarantee room inside# Runner::DEFAULT_MAX_TOOL_RESULT_CHARS: ordinary comment pages, uncapped# metadata and escaping can still take a whole result past that budget.- MAX_ATTACHMENTS = 10+ MAX_ATTACHMENTS = Tickets::Reading::MAX_ATTACHMENTSMAX_ATTACHMENT_TEXT_CHARS = 4_000# Bounds the candidate list of an ambiguous number. Within one project a@@ -148,7 +149,7 @@ module Lalabase# its reach. Set centrally so no branch can forget it.result.coverage ||= coverage_for(context, area: :tickets, only_project: chosen)result- rescue InvalidOption => e+ rescue Tickets::Reading::InvalidOption => eResult.invalid_input(e.message)end@@ -232,13 +233,14 @@ module Lalabasefull_text_limit = context.chat ? MAX_ASSISTANT_FULL_TEXT_CHARS : MAX_FULL_TEXT_CHARSserializer = Tickets::Serializer.new(current_user: context.actor)- comments = options.post_id ? one_post(serializer, ticket, options, limit: full_text_limit) : post_page(serializer, ticket, options)+ reading = Tickets::Reading.new(serializer: serializer)+ comments = options.post_id ? one_post(reading, ticket, options, limit: full_text_limit) : post_page(reading, ticket, options)return comments if comments.is_a?(Result)description_cap = options.full_text ? full_text_limit : MAX_BODY_CHARSpayload = cap_description(serializer.full(ticket, posts: false), description_cap).merge(comments)- .merge(attachment_page(serializer, ticket, options.attachments_page))+ .merge(attachment_page(reading, ticket, options.paging.attachments_page))# Cite the ticket: the citation's area ('tickets') is what makes the answer# rights-gated for OTHER readers of the shared chat, not only for the asker.# Keep the ids of comments actually handed to the model, including private@@ -248,34 +250,21 @@ module Lalabaseendprivate_class_method :serve- # One page out of the reader's readable comments; posts_total is their count,- # posts_truncated says the page is a part of them.- def self.post_page(serializer, ticket, options)- per_page = options.posts_per_page- entries, total = serializer.posts_page(ticket, page: options.posts_page, per_page: per_page,- newest: options.newest)- {- posts: entries.map { |post| cap_post(post, MAX_BODY_CHARS) },- posts_total: total,- posts_truncated: total > entries.size,- posts_page: options.posts_page,- posts_per_page: per_page,- posts_pages: (total + per_page - 1) / per_page,- posts_order: options.newest ? 'newest' : 'oldest'- }+ # Tickets::Reading#post_page with each comment capped.+ def self.post_page(reading, ticket, options)+ page = reading.post_page(ticket, options.paging)+ page.merge(posts: page[:posts].map { |post| cap_post(post, MAX_BODY_CHARS) })endprivate_class_method :post_page# The one comment of post_id, within the surface's full-text limit, picked# from the reader's readable comments of THIS ticket. Hidden, foreign and# missing comments all answer "No comment found".- def self.one_post(serializer, ticket, options, limit:)- post = serializer.readable_post(ticket, options.post_id)- return no_match("No comment found for #{options.post_id}.") if post.nil?+ def self.one_post(reading, ticket, options, limit:)+ page = reading.one_post(ticket, options.post_id)+ return no_match("No comment found for #{options.post_id}.") if page.nil?- total = serializer.readable_posts_count(ticket)- { posts: [cap_post(post, limit)], posts_total: total, posts_truncated: total > 1,- post_id: options.post_id }+ page.merge(posts: page[:posts].map { |post| cap_post(post, limit) }, post_id: options.post_id)endprivate_class_method :one_post@@ -283,19 +272,11 @@ module Lalabase# come from their own serializer method, because #full is shared with the HTTP# API and must not grow a body of file text there.#- # A page of MAX_ATTACHMENTS, bounded IN the query; attachments_total is the- # separate COUNT, attachments_truncated says the page is a part: a list that- # was silently cut is a list the model reads as complete.- def self.attachment_page(serializer, ticket, page)- files = serializer.attachments(ticket, limit: MAX_ATTACHMENTS, offset: (page - 1) * MAX_ATTACHMENTS)- total = serializer.attachments_total(ticket)- {- attachments: files.map { |file| cap_attachment(file) },- attachments_total: total,- attachments_truncated: total > files.size,- attachments_page: page,- attachments_pages: (total + MAX_ATTACHMENTS - 1) / MAX_ATTACHMENTS- }+ # Tickets::Reading#attachment_page (bounded in the query, with the honest+ # total) with each file's text capped.+ def self.attachment_page(reading, ticket, page)+ files = reading.attachment_page(ticket, page)+ files.merge(attachments: files[:attachments].map { |file| cap_attachment(file) })endprivate_class_method :attachment_page@@ -352,70 +333,31 @@ module Lalabaseendprivate_class_method :cap_post- # Strict like Notifications::InboxQuery: a value that cannot be read is- # refused, never quietly replaced by a default.+ # Paging is Tickets::Reading's (MCP clamps posts_per_page, as it always+ # did); full_text and post_id belong to this tool.def self.parse_options(args)Options.new(- posts_page: page_arg(args[:posts_page], 'posts_page'),- posts_per_page: per_page_arg(args[:posts_per_page]),- newest: order_arg(args[:posts_order]),- attachments_page: page_arg(args[:attachments_page], 'attachments_page'),+ paging: Tickets::Reading.options(args, over_max: :clamp),full_text: full_text_arg(args[:full_text]),post_id: post_id_arg(args[:post_id]))endprivate_class_method :parse_options- def self.integer_arg(value, name)- return nil if value.nil? || (value.is_a?(String) && value.strip.empty?)- return value if value.is_a?(Integer)-- (value.is_a?(String) && Integer(value.strip, 10, exception: false)) ||- raise(InvalidOption, "invalid #{name} #{value.inspect} (expected a whole number)")- end- private_class_method :integer_arg-- def self.page_arg(value, name)- number = integer_arg(value, name)- return 1 if number.nil?- return number if number.between?(1, MAX_PAGE)-- raise InvalidOption, "invalid #{name} #{value.inspect} (1 to #{MAX_PAGE})"- end- private_class_method :page_arg-- def self.per_page_arg(value)- number = integer_arg(value, 'posts_per_page')- return MAX_POSTS if number.nil?- raise InvalidOption, "invalid posts_per_page #{value.inspect} (at least 1)" if number < 1-- [number, MAX_POSTS].min- end- private_class_method :per_page_arg-- def self.order_arg(value)- raw = value.to_s.strip- return false if raw.empty?- raise InvalidOption, "invalid posts_order #{value.inspect} (oldest or newest)" unless POST_ORDERS.include?(raw)-- raw == 'newest'- end- private_class_method :order_arg-# A boolean, as the MCP schema declares it: the in-app assistant calls the# tool without that schema check, and a "true" there must not read as false.def self.full_text_arg(value)return false if value.nil? || value == '' || value == falsereturn true if value == true- raise InvalidOption, "invalid full_text #{value.inspect} (true or false)"+ raise Tickets::Reading::InvalidOption, "invalid full_text #{value.inspect} (true or false)"endprivate_class_method :full_text_argdef self.post_id_arg(value)raw = value.to_s.stripreturn nil if raw.empty?- raise InvalidOption, 'invalid post_id format' unless raw.match?(UUID_FORMAT)+ raise Tickets::Reading::InvalidOption, 'invalid post_id format' unless raw.match?(UUID_FORMAT)rawenddiff --git a/app/services/tickets/reading.rb b/app/services/tickets/reading.rbnew file mode 100644index 0000000..ae402a5--- /dev/null+++ b/app/services/tickets/reading.rb@@ -0,0 +1,141 @@+# frozen_string_literal: true++# The ticket view in pages, one rule for two surfaces (cli_rest_plan D5): the+# MCP get_ticket tool and GET /api/v1/tickets/:id (plus the number route and+# GET /api/v1/tickets/:ticket_id/posts/:id) parse the same options and build+# the same pages. Each surface keeps its own envelope: the MCP caps (body+# lengths, attachment text, assistant limits, citations) stay in the tool, the+# REST controllers hand the pages out uncut.+#+# Visibility is the serializer's: every page and count comes out of+# ticket.posts.readable_by, so posts_total never counts a comment the reader+# may not see. The attachments are the ticket's OWN files (TicketDocument);+# files on comments are not part of this list.+#+# Entry point: options+module Tickets+ class Reading+ MAX_POSTS = 50+ MAX_ATTACHMENTS = 10+ # Far beyond any real ticket, close enough to keep the OFFSET in range+ # (the same reasoning as Notifications::InboxQuery::MAX_PAGE).+ MAX_PAGE = 100_000+ POST_ORDERS = %w[oldest newest].freeze+ # Any one of these switches the REST answer to pages.+ PAGING_KEYS = %w[posts_page posts_per_page posts_order attachments_page].freeze++ Options = Struct.new(:posts_page, :posts_per_page, :newest, :attachments_page, keyword_init: true)+ class InvalidOption < ArgumentError; end++ # Strict like Notifications::InboxQuery: a value that cannot be read is+ # refused, never quietly replaced by a default. Only a posts_per_page above+ # MAX_POSTS differs by surface: MCP has always clamped it (`over_max:+ # :clamp`), REST refuses it (`:refuse`).+ #+ # @param args [Hash] symbol keys posts_page, posts_per_page, posts_order, attachments_page+ # @raise [InvalidOption] with a message naming the argument+ def self.options(args, over_max: :clamp)+ Options.new(+ posts_page: page_arg(args[:posts_page], 'posts_page'),+ posts_per_page: per_page_arg(args[:posts_per_page], over_max),+ newest: order_arg(args[:posts_order]),+ attachments_page: page_arg(args[:attachments_page], 'attachments_page')+ )+ end++ # @param params [#key?] request parameters+ def self.paging_requested?(params)+ PAGING_KEYS.any? { |key| params.key?(key) }+ end++ def initialize(serializer:)+ @serializer = serializer+ end++ # One page out of the reader's readable comments; posts_total is their count,+ # posts_truncated says the page is a part of them.+ def post_page(ticket, options)+ per_page = options.posts_per_page+ entries, total = @serializer.posts_page(ticket, page: options.posts_page, per_page: per_page,+ newest: options.newest)+ {+ posts: entries,+ posts_total: total,+ posts_truncated: total > entries.size,+ posts_page: options.posts_page,+ posts_per_page: per_page,+ posts_pages: (total + per_page - 1) / per_page,+ posts_order: options.newest ? 'newest' : 'oldest'+ }+ end++ # One comment the reader may read on THIS ticket, or nil: hidden, foreign and+ # missing comments read alike.+ def post(ticket, id)+ @serializer.readable_post(ticket, id)+ end++ # The comment of `id` as a page of one, with the count of readable comments,+ # or nil like #post.+ def one_post(ticket, id)+ entry = post(ticket, id)+ return nil if entry.nil?++ total = @serializer.readable_posts_count(ticket)+ { posts: [entry], posts_total: total, posts_truncated: total > 1 }+ end++ # A page of MAX_ATTACHMENTS, bounded IN the query; attachments_total is the+ # separate COUNT, attachments_truncated says the page is a part: a list that+ # was silently cut is a list a reader takes as complete.+ def attachment_page(ticket, page)+ files = @serializer.attachments(ticket, limit: MAX_ATTACHMENTS, offset: (page - 1) * MAX_ATTACHMENTS)+ total = @serializer.attachments_total(ticket)+ {+ attachments: files,+ attachments_total: total,+ attachments_truncated: total > files.size,+ attachments_page: page,+ attachments_pages: (total + MAX_ATTACHMENTS - 1) / MAX_ATTACHMENTS+ }+ end++ def self.integer_arg(value, name)+ return nil if value.nil? || (value.is_a?(String) && value.strip.empty?)+ return value if value.is_a?(Integer)++ (value.is_a?(String) && Integer(value.strip, 10, exception: false)) ||+ raise(InvalidOption, "invalid #{name} #{value.inspect} (expected a whole number)")+ end+ private_class_method :integer_arg++ def self.page_arg(value, name)+ number = integer_arg(value, name)+ return 1 if number.nil?+ return number if number.between?(1, MAX_PAGE)++ raise InvalidOption, "invalid #{name} #{value.inspect} (1 to #{MAX_PAGE})"+ end+ private_class_method :page_arg++ def self.per_page_arg(value, over_max)+ number = integer_arg(value, 'posts_per_page')+ return MAX_POSTS if number.nil?+ raise InvalidOption, "invalid posts_per_page #{value.inspect} (at least 1)" if number < 1+ return number if number <= MAX_POSTS+ return MAX_POSTS if over_max == :clamp++ raise InvalidOption, "invalid posts_per_page #{value.inspect} (1 to #{MAX_POSTS})"+ end+ private_class_method :per_page_arg++ def self.order_arg(value)+ raw = value.to_s.strip+ return false if raw.empty?+ raise InvalidOption, "invalid posts_order #{value.inspect} (oldest or newest)" unless POST_ORDERS.include?(raw)++ raw == 'newest'+ end+ private_class_method :order_arg+ end+enddiff --git a/config/routes.rb b/config/routes.rbindex 7558c50..a98fdf5 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -929,6 +929,11 @@ Rails.application.routes.draw doget 'time_sessions/open', to: 'time_sessions#open'resources :projects, only: %i[index] doresources :tickets, only: %i[index create]+ # REST R1: a ticket by the number users see. format: false and the+ # constraint keep "1.5" one segment: a malformed number (JSON 404), not+ # number 1 as format "5" nor a route miss.+ get 'tickets/number/:number', to: 'tickets#by_number', as: :ticket_by_number, format: false,+ constraints: { number: %r{[^/]+} }get :ticket_attribute_definitions, on: :memberendresources :tickets, only: %i[show update] do@@ -937,7 +942,7 @@ Rails.application.routes.draw doget :attachmentsendresources :time_sessions, only: %i[index create]- resources :posts, only: %i[create]+ resources :posts, only: %i[create show]endendenddiff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rbindex a799709..74c1b03 100644--- a/spec/contracts/mcp_contract_recorder.rb+++ b/spec/contracts/mcp_contract_recorder.rb@@ -475,11 +475,28 @@ module McpContract# Each request from its own line (Prosopite). `show` is the ticket without# paging parameters: its body must stay what gboyke/lalabase-mcp reads.+ # The answers after `show` are the R1 additions: a page, a refused option,+ # the ticket by number (and a number that is not there or not readable),+ # one comment and a missing one.def rest_ticket_view_callslogin = "/api/v1/tickets/#{id(:login_ticket)}"+ by_number = ->(project, number) { "/api/v1/projects/#{id(project)}/tickets/number/#{number}" }{- 'list' => rest_get(:read, "/api/v1/projects/#{id(:website)}/tickets"),- 'show' => rest_get(:read, login)+ # Filtered to Ben's one ticket: the writes above left both website+ # tickets with the same updated_at, and the list has no second sort key.+ 'list' => rest_get(:read, "/api/v1/projects/#{id(:website)}/tickets?assignee=#{id(:ben)}"),+ 'show' => rest_get(:read, login),+ # Oldest first: the second comment was made with its own clock tick, while+ # the comments the recorded writes added share one second and would be+ # ordered by their random ids.+ 'show_paged' => rest_get(:read, "#{login}?posts_per_page=1&posts_page=2&attachments_page=1"),+ 'show_invalid_paging' => rest_get(:read, "#{login}?posts_order=random"),+ 'by_number' => rest_get(:read, by_number.call(:website, 1)),+ 'by_number_not_found' => rest_get(:read, by_number.call(:website, 999)),+ # No read access to the handbook's tickets: answered like a missing number.+ 'by_number_hidden' => rest_get(:read, by_number.call(:handbook, 1)),+ 'post' => rest_get(:read, "#{login}/posts/#{id(:first_post)}"),+ 'post_not_found' => rest_get(:read, "#{login}/posts/#{id(:missing)}")}enddiff --git a/spec/fixtures/mcp_contract.json b/spec/fixtures/mcp_contract.jsonindex 9c7fb5d..8e0621c 100644--- a/spec/fixtures/mcp_contract.json+++ b/spec/fixtures/mcp_contract.json@@ -1,9 +1,9 @@{"header": {"regenerate": "RAILS_ENV=test bin/rails mcp:contract",- "core_commit": "2600e2edcf8a5ed972e35fa0e623ccad47912b8a",+ "core_commit": "d65653e2f2f97830d0a0bd7eeec32e61ee04710a","core_dirty": true,- "contract_sha256": "105ebdc25cb8a00cc75223833128be305a8b309da1ae4277a7e10333ae426cf3"+ "contract_sha256": "74378fb5a0725c5d4d72633c74372240663e936e2e0b126d48b769d9e094fbf5"},"contract": {"mcp": {@@ -2992,7 +2992,7 @@"all_projects": true}],- "api_version": "1.1.0",+ "api_version": "1.2.0","capabilities": ["error_codes","idempotency",@@ -3003,12 +3003,15 @@"notifications.mark_as_read","organisations.list","posts.create",+ "posts.show","projects.list","projects.ticket_attribute_definitions","tickets.activities","tickets.attachments",+ "tickets.by_number","tickets.create","tickets.list",+ "tickets.paging","tickets.show","tickets.update","time_sessions.create",@@ -3049,7 +3052,7 @@"all_projects": true}],- "api_version": "1.1.0",+ "api_version": "1.2.0","capabilities": ["error_codes","idempotency",@@ -3060,12 +3063,15 @@"notifications.mark_as_read","organisations.list","posts.create",+ "posts.show","projects.list","projects.ticket_attribute_definitions","tickets.activities","tickets.attachments",+ "tickets.by_number","tickets.create","tickets.list",+ "tickets.paging","tickets.show","tickets.update","time_sessions.create",@@ -3596,7 +3602,7 @@"list": {"token": "read","request": {- "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/tickets"+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/tickets?assignee=00000000-0000-4000-8000-000000000012"},"response": {"status": 200,@@ -3632,43 +3638,331 @@},"created_at": "2026-01-05T09:21:00Z","updated_at": "2026-01-05T09:36:00Z"+ }+ ],+ "meta": {+ "page": 1,+ "per_page": 25,+ "total": 1,+ "available_statuses": [+ "new",+ "in_progress",+ "resolved",+ "closed",+ "backlog"+ ]+ }+ }+ }+ },+ "show": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041"+ },+ "response": {+ "status": 200,+ "body": {+ "data": {+ "id": "00000000-0000-4000-8000-000000000041",+ "number": 1,+ "title": "Login bricht ab",+ "status": "in_progress",+ "status_functions": [+ "is_in_progress"+ ],+ "ticket_type": "support",+ "parent_id": null,+ "assignees": [+ {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ {+ "id": "00000000-0000-4000-8000-000000000012",+ "name": "Ben Berger"+ },+ {+ "id": "00000000-0000-4000-8000-000000000013",+ "name": "Carla Conrad"+ }+ ],+ "creator": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"},- {- "id": "00000000-0000-4000-8000-000000000042",- "number": 2,- "title": "Export als CSV und XLSX",+ "created_at": "2026-01-05T09:21:00Z",+ "updated_at": "2026-01-05T09:36:00Z",+ "summary": null,+ "description_html": "Nach dem Absenden bleibt die Seite weiß.",+ "description_text": "Nach dem Absenden bleibt die Seite weiß.",+ "custom_attributes": {"status": "in_progress",- "status_functions": [- "is_in_progress"- ],- "ticket_type": "support",- "parent_id": null,- "assignees": [- {+ "priority": "high"+ },+ "project": {+ "id": "00000000-0000-4000-8000-000000000031",+ "name": "Website-Relaunch"+ },+ "posts": [+ {+ "id": "00000000-0000-4000-8000-000000000051",+ "author": {+ "id": "00000000-0000-4000-8000-000000000012",+ "name": "Ben Berger"+ },+ "body_html": "Tritt nur in Safari auf.",+ "body_text": "Tritt nur in Safari auf.",+ "is_private": false,+ "attachments_count": 1,+ "created_at": "2026-01-05T09:25:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "00000000-0000-4000-8000-000000000052",+ "author": {"id": "00000000-0000-4000-8000-000000000011","name": "Anna Albers"- }- ],- "creator": {+ },+ "body_html": "Ich schaue es mir an.",+ "body_text": "Ich schaue es mir an.",+ "is_private": false,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:26:00Z",+ "updated_at": "2026-01-05T09:26:00Z"+ },+ {+ "id": "<generated-id-1>",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "Behoben in 2.4.1.",+ "body_text": "Behoben in 2.4.1.",+ "is_private": false,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "<generated-id-2>",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p>line one<br>line two</p><p>see <file.txt> &lt;tag&gt;</p>",+ "body_text": "line one\nline two\n\nsee <file.txt> <tag>",+ "is_private": false,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "<generated-id-3>",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p><b>bold</b></p>",+ "body_text": "bold",+ "is_private": false,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "<generated-id-4>",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "<p><private></p>",+ "body_text": "<private>",+ "is_private": true,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ },+ {+ "id": "<generated-id-7>",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "Per REST, einmal.",+ "body_text": "Per REST, einmal.",+ "is_private": false,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:36:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ ]+ },+ "permissions": {+ "is_account_admin": false,+ "tickets": {+ "read": true,+ "write": true+ },+ "documents": {+ "read": false,+ "write": false+ },+ "posts": {+ "can_create": true,+ "can_update_own": true,+ "can_destroy_own": true+ },+ "time_sessions": {+ "can_view_own": true,+ "can_view_all": false,+ "can_create_own": true,+ "can_edit_own": true,+ "can_edit_all": false,+ "can_delete_own": true,+ "can_delete_all": false+ },+ "activities": {+ "read": true+ }+ }+ }+ }+ },+ "show_paged": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041?posts_per_page=1&posts_page=2&attachments_page=1"+ },+ "response": {+ "status": 200,+ "body": {+ "data": {+ "id": "00000000-0000-4000-8000-000000000041",+ "number": 1,+ "title": "Login bricht ab",+ "status": "in_progress",+ "status_functions": [+ "is_in_progress"+ ],+ "ticket_type": "support",+ "parent_id": null,+ "assignees": [+ {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ {"id": "00000000-0000-4000-8000-000000000012","name": "Ben Berger"},- "created_at": "2026-01-05T09:22:00Z",- "updated_at": "2026-01-05T09:36:00Z"+ {+ "id": "00000000-0000-4000-8000-000000000013",+ "name": "Carla Conrad"+ }+ ],+ "creator": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "created_at": "2026-01-05T09:21:00Z",+ "updated_at": "2026-01-05T09:36:00Z",+ "summary": null,+ "description_html": "Nach dem Absenden bleibt die Seite weiß.",+ "description_text": "Nach dem Absenden bleibt die Seite weiß.",+ "custom_attributes": {+ "status": "in_progress",+ "priority": "high"+ },+ "project": {+ "id": "00000000-0000-4000-8000-000000000031",+ "name": "Website-Relaunch"+ },+ "posts": [+ {+ "id": "00000000-0000-4000-8000-000000000052",+ "author": {+ "id": "00000000-0000-4000-8000-000000000011",+ "name": "Anna Albers"+ },+ "body_html": "Ich schaue es mir an.",+ "body_text": "Ich schaue es mir an.",+ "is_private": false,+ "attachments_count": 0,+ "created_at": "2026-01-05T09:26:00Z",+ "updated_at": "2026-01-05T09:26:00Z"+ }+ ],+ "posts_total": 7,+ "posts_truncated": true,+ "posts_page": 2,+ "posts_per_page": 1,+ "posts_pages": 7,+ "posts_order": "oldest",+ "attachments": [+ {+ "id": "<generated-id-8>",+ "filename": "test_document.pdf",+ "content_type": "application/pdf",+ "byte_size": 452,+ "text": null,+ "text_status": "unavailable"+ }+ ],+ "attachments_total": 1,+ "attachments_truncated": false,+ "attachments_page": 1,+ "attachments_pages": 1+ },+ "permissions": {+ "is_account_admin": false,+ "tickets": {+ "read": true,+ "write": true+ },+ "documents": {+ "read": false,+ "write": false+ },+ "posts": {+ "can_create": true,+ "can_update_own": true,+ "can_destroy_own": true+ },+ "time_sessions": {+ "can_view_own": true,+ "can_view_all": false,+ "can_create_own": true,+ "can_edit_own": true,+ "can_edit_all": false,+ "can_delete_own": true,+ "can_delete_all": false+ },+ "activities": {+ "read": true}- ],- "meta": {- "page": 1,- "per_page": 25,- "total": 2}}}},- "show": {+ "show_invalid_paging": {"token": "read","request": {- "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041"+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041?posts_order=random"+ },+ "response": {+ "status": 422,+ "body": {+ "error": "invalid_input",+ "code": "invalid_input",+ "message": "invalid posts_order \"random\" (oldest or newest)"+ }+ }+ },+ "by_number": {+ "token": "read",+ "request": {+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/tickets/number/1"},"response": {"status": 200,@@ -3838,6 +4132,69 @@}}}+ },+ "by_number_not_found": {+ "token": "read",+ "request": {+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000031/tickets/number/999"+ },+ "response": {+ "status": 404,+ "body": {+ "error": "not_found",+ "code": "not_found"+ }+ }+ },+ "by_number_hidden": {+ "token": "read",+ "request": {+ "path": "/api/v1/projects/00000000-0000-4000-8000-000000000033/tickets/number/1"+ },+ "response": {+ "status": 404,+ "body": {+ "error": "not_found",+ "code": "not_found"+ }+ }+ },+ "post": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts/00000000-0000-4000-8000-000000000051"+ },+ "response": {+ "status": 200,+ "body": {+ "data": {+ "id": "00000000-0000-4000-8000-000000000051",+ "author": {+ "id": "00000000-0000-4000-8000-000000000012",+ "name": "Ben Berger"+ },+ "body_html": "Tritt nur in Safari auf.",+ "body_text": "Tritt nur in Safari auf.",+ "is_private": false,+ "attachments_count": 1,+ "created_at": "2026-01-05T09:25:00Z",+ "updated_at": "2026-01-05T09:36:00Z"+ }+ }+ }+ },+ "post_not_found": {+ "token": "read",+ "request": {+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/posts/00000000-0000-4000-8000-000000000999"+ },+ "response": {+ "status": 404,+ "body": {+ "error": "not_found",+ "code": "not_found"+ }+ }}}}diff --git a/spec/requests/api/mcp_spec.rb b/spec/requests/api/mcp_spec.rbindex 203aff9..fa7ff06 100644--- a/spec/requests/api/mcp_spec.rb+++ b/spec/requests/api/mcp_spec.rb@@ -730,7 +730,7 @@ RSpec.describe 'API MCP endpoint', type: :request doendit 'caps the number of posts and flags truncation (D9 caps)' do- stub_const('Lalabase::Tools::GetTicket::MAX_POSTS', 1)+ stub_const('Tickets::Reading::MAX_POSTS', 1)Prosopite.pauseActsAsTenant.with_tenant(organisation) do2.times { |i| create(:post, ticket: ticket, user: user, organisation: organisation, content: "Reply #{i}") }diff --git a/spec/requests/api/v1/capabilities_spec.rb b/spec/requests/api/v1/capabilities_spec.rbindex 6526449..1b5a6f0 100644--- a/spec/requests/api/v1/capabilities_spec.rb+++ b/spec/requests/api/v1/capabilities_spec.rb@@ -33,7 +33,7 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request doit 'names the API version and the capabilities beside the existing fields' dodata = me(token(read_only: false))- expect(data['api_version']).to eq('1.1.0')+ expect(data['api_version']).to eq('1.2.0')expect(data['capabilities']).to eq(Api::V1::Capabilities.names)expect(data.keys).to include('user', 'token', 'scoped_organisations')end@@ -46,7 +46,8 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request doexpect(Api::V1::Capabilities.names).to include('me.show', 'organisations.list', 'projects.list', 'tickets.list', 'tickets.create', 'tickets.show','tickets.update', 'tickets.attachments', 'posts.create', 'time_sessions.create',- 'notifications.list', 'notifications.mark_as_read', 'idempotency', 'error_codes'+ 'notifications.list', 'notifications.mark_as_read', 'idempotency', 'error_codes',+ 'tickets.by_number', 'posts.show', 'tickets.paging')enddiff --git a/spec/requests/api/v1/ticket_view_spec.rb b/spec/requests/api/v1/ticket_view_spec.rbnew file mode 100644index 0000000..115c038--- /dev/null+++ b/spec/requests/api/v1/ticket_view_spec.rb@@ -0,0 +1,358 @@+# frozen_string_literal: true++require 'rails_helper'++# REST R1: the ticket view without MCP. The status list on the ticket list,+# opt-in pages of comments and attachments on GET /tickets/:id, one comment by+# id and the ticket by its number. Pages come from Tickets::Reading, the same+# service the MCP get_ticket tool uses, so REST is compared against MCP here.+#+# Rights: only comments the reader may read are listed, counted or served one+# by one. A hidden comment, a foreign one and a missing one answer the same+# 404; so do a missing number, a number in a project beyond the token's reach+# or the reader's access, an unreadable ticket and another organisation.+RSpec.describe 'REST ticket view', :ci_guard, type: :request do+ let(:organisation) { create(:organisation) }+ let(:role) { create(:role, organisation: organisation) }+ let(:project) { create(:project, organisation: organisation) }+ let(:not_found_body) { { error: 'not_found', code: 'not_found' }.to_json }++ def member(role_for = role, tickets: 'read_only', on: project)+ Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ user = create(:user)+ create(:membership, user: user, organisation: organisation, role: role_for, active: true)+ create(:project_permission, user: user, project: on, tickets_access: tickets) if tickets+ user+ end+ end+ end++ let(:author) { member }+ let(:addressee) { member }+ let(:other) { member }+ let(:admin_role) { Prosopite.pause { ActsAsTenant.with_tenant(organisation) { create(:admin_role, organisation: organisation) } } }+ let(:admin) { member(admin_role, tickets: nil) }+ let(:ticket) { create(:ticket, project: project, organisation: organisation, creator: author) }+ let(:long_text) { "#{'Lang ' * 2_000}Ende" }++ # Seven comments, two of them private for the addressee, in a fixed order; the+ # first public one is longer than MCP's 8,000-character cap.+ let!(:posts) do+ Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ Projects::DefaultAttributeService.new(project).call+ base = 2.hours.ago+ Array.new(7) do |i|+ private_one = [2, 5].include?(i)+ create(:post, ticket: ticket, organisation: organisation, user: author,+ content: i.zero? ? long_text : "Kommentar #{i}",+ is_private: private_one, visible_to_user: (addressee if private_one),+ create_embeddings: false, created_at: base + i.minutes)+ end+ end+ end+ end++ after { ActsAsTenant.current_tenant = nil }++ def token_for(user, **options)+ Prosopite.pause do+ create(:personal_access_token, user: user, organisations: [organisation], **options).token+ end+ end++ def get_json(user, path, params = {}, token: nil)+ get path, params: params, headers: { 'Authorization' => "Bearer #{token || token_for(user)}" }+ response.parsed_body+ end++ def ticket_path(id = ticket.id) = "/api/v1/tickets/#{id}"+ def number_path(number, project_id: project.id) = "/api/v1/projects/#{project_id}/tickets/number/#{number}"++ def mcp_answer(user, tool, **args)+ ActsAsTenant.with_tenant(organisation) do+ context = Lalabase::Tools::Context.new(actor: user, organisation: organisation, project: project)+ JSON.parse(Lalabase::Tools.const_get(tool).execute(args: args, context: context).content)+ end+ end++ def expect_not_found+ expect(response).to have_http_status(:not_found)+ expect(response.body).to eq(not_found_body)+ end++ let(:page_keys) do+ %w[posts posts_total posts_truncated posts_page posts_per_page posts_pages posts_order+ attachments attachments_total attachments_truncated attachments_page attachments_pages]+ end++ describe 'GET /projects/:project_id/tickets meta.available_statuses' do+ it 'lists the statuses MCP list_tickets names for the same project' do+ body = get_json(other, "/api/v1/projects/#{project.id}/tickets")+ expected = mcp_answer(other, :ListTickets).dig('meta', 'available_statuses')+ expect(expected).to be_present+ expect(body.dig('meta', 'available_statuses')).to eq(expected)+ expect(body['meta'].keys).to eq(%w[page per_page total available_statuses])+ end+ end++ describe 'GET /tickets/:id without paging parameters' do+ it 'keeps the body it always had: the whole ticket with every readable comment, uncut' do+ body = get_json(other, ticket_path)+ expected = Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ Tickets::Serializer.new(current_user: other).full(Ticket.find(ticket.id)).as_json+ end+ end+ expect(body.keys).to eq(%w[data permissions])+ expect(body['data']).to eq(expected)+ expect(body['data'].keys).not_to include(*page_keys.excluding('posts'))+ expect(body.dig('data', 'posts', 0, 'body_text')).to eq(long_text)+ end+ end++ describe 'GET /tickets/:id with paging parameters' do+ # One example per reader: Prosopite watches each request on its own.+ { other: 5, addressee: 7, admin: 7 }.each do |reader, total|+ it "pages and counts what the #{reader} may read, like MCP get_ticket" do+ user = public_send(reader)+ body = get_json(user, ticket_path, { posts_per_page: '3', posts_order: 'newest' })+ mcp = mcp_answer(user, :GetTicket, ticket_id: ticket.id, posts_per_page: 3, posts_order: 'newest')++ expect(response).to have_http_status(:ok)+ expect(body['data']['posts_total']).to eq(total)+ expect(body['data'].slice(*page_keys)).to eq(mcp.slice(*page_keys))+ expect(body.keys).to eq(%w[data permissions])+ end+ end++ it 'hands out a whole comment where MCP cuts it' do+ body = get_json(other, ticket_path, { posts_page: 1 })+ expect(body.dig('data', 'posts', 0, 'body_text')).to eq(long_text)+ expect(mcp_answer(other, :GetTicket, ticket_id: ticket.id).dig('posts', 0, 'body_text').length)+ .to be < long_text.length+ end++ it 'turns the pages without skipping or repeating a readable comment' do+ first = get_json(other, ticket_path, { posts_per_page: 3, posts_page: 1 }).dig('data', 'posts')+ second = get_json(other, ticket_path, { posts_per_page: 3, posts_page: 2 }).dig('data', 'posts')+ expected = posts.reject(&:is_private?).map(&:id)+ expect((first + second).pluck('id')).to eq(expected)+ end++ it 'answers a page past the end with no comments and the true totals' do+ body = get_json(other, ticket_path, { posts_page: 9, posts_per_page: 2 })['data']+ expect(body.slice('posts', 'posts_total', 'posts_pages', 'posts_truncated', 'posts_page'))+ .to eq('posts' => [], 'posts_total' => 5, 'posts_pages' => 3, 'posts_truncated' => true, 'posts_page' => 9)+ mcp = mcp_answer(other, :GetTicket, ticket_id: ticket.id, posts_page: 9, posts_per_page: 2)+ expect(body.slice(*page_keys)).to eq(mcp.slice(*page_keys))+ end++ # One example per option: Prosopite reads one call site asked four times as an N+1.+ { 'posts_page' => '1', 'posts_per_page' => '1', 'posts_order' => 'oldest', 'attachments_page' => '1' }.each do |key, value|+ it "switches to pages with #{key} alone" do+ body = get_json(other, ticket_path, { key => value })+ expect(body['data'].keys).to include(*page_keys)+ end+ end++ let(:other_token) { token_for(other) }++ { { posts_per_page: '51' } => 'posts_per_page', { posts_page: '0' } => 'posts_page',+ { posts_order: 'random' } => 'posts_order', { attachments_page: 'x' } => 'attachments_page',+ { posts_page: ['1'] } => 'posts_page' }.each do |params, name|+ it "refuses #{params.inspect} with 422 invalid_input" do+ body = get_json(other, ticket_path, params)+ expect(response).to have_http_status(:unprocessable_content)+ expect(body.slice('error', 'code')).to eq('error' => 'invalid_input', 'code' => 'invalid_input')+ expect(body['message']).to include(name)+ end+ end++ it 'refuses an invalid option the same way whether the ticket exists or not' do+ get_json(other, ticket_path(SecureRandom.uuid), { posts_order: 'random' }, token: other_token)+ missing = [response.status, response.body]+ get_json(other, ticket_path, { posts_order: 'random' }, token: other_token)+ expect([response.status, response.body]).to eq(missing)+ end++ context 'with attachments' do+ let!(:files) do+ Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ # A file on a private comment the reader cannot see: never in the list.+ hidden = PostDocument.new(post: posts[2], organisation: organisation, create_embeddings: false)+ hidden.post_document_file.attach(io: StringIO.new('Geheim'), filename: 'geheim.txt',+ content_type: 'text/plain', identify: false)+ hidden.save!+ Array.new(11) do+ document = TicketDocument.new(ticket: ticket, organisation: organisation, create_embeddings: false)+ document.ticket_document_file.attach(io: StringIO.new('Inhalt'), filename: 'notiz.txt',+ content_type: 'text/plain', identify: false)+ document.save!+ document+ end+ end+ end+ end++ it 'pages the ticket files like MCP, never a file of a comment' do+ body = get_json(other, ticket_path, { attachments_page: 2 })['data']+ mcp = mcp_answer(other, :GetTicket, ticket_id: ticket.id, attachments_page: 2)+ attachment_keys = page_keys.grep(/\Aattachments/)+ expect(body.slice(*attachment_keys)).to eq(mcp.slice(*attachment_keys))+ expect(body.slice('attachments_total', 'attachments_pages', 'attachments_page'))+ .to eq('attachments_total' => 11, 'attachments_pages' => 2, 'attachments_page' => 2)+ expect(body['attachments'].size).to eq(1)+ expect(response.body).not_to include('geheim.txt')+ end+ end+ end++ describe 'GET /tickets/:ticket_id/posts/:id' do+ def post_path(post_id, ticket_id: ticket.id) = "/api/v1/tickets/#{ticket_id}/posts/#{post_id}"++ let(:private_post) { posts[2] }++ it 'serves one readable comment whole, as the ticket lists it' do+ body = get_json(other, post_path(posts[0].id))+ listed = get_json(other, ticket_path).dig('data', 'posts', 0)+ expect(response).to have_http_status(:ok)+ expect(body).to eq('data' => listed)+ expect(body.dig('data', 'body_text')).to eq(long_text)+ end++ it 'serves a private comment to its addressee' do+ body = get_json(addressee, post_path(private_post.id))+ expect(body.dig('data', 'id')).to eq(private_post.id)+ end++ it 'serves a private comment to an account admin' do+ expect(get_json(admin, post_path(private_post.id)).dig('data', 'id')).to eq(private_post.id)+ end++ it 'hides a private comment from another member like a missing one' do+ get_json(other, post_path(private_post.id))+ expect_not_found+ end++ it 'answers a missing and a malformed comment id the same way' do+ get_json(other, post_path(SecureRandom.uuid))+ expect_not_found+ get_json(other, post_path('abc'))+ expect_not_found+ end++ it 'does not serve a comment through another ticket' do+ sibling = Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) { create(:ticket, project: project, organisation: organisation, creator: author) }+ end+ get_json(other, post_path(posts[1].id, ticket_id: sibling.id))+ expect_not_found+ end++ it 'does not serve a comment of a ticket the reader may not read' do+ outsider = member(tickets: nil)+ get_json(outsider, post_path(posts[1].id))+ expect_not_found+ end+ end++ describe 'GET /projects/:project_id/tickets/number/:number' do+ it 'answers exactly what GET /tickets/:id answers for the same ticket' do+ token = token_for(other)+ by_id = get_json(other, ticket_path, {}, token: token)+ expect(get_json(other, number_path(ticket.number), {}, token: token)).to eq(by_id)+ expect(response).to have_http_status(:ok)+ end++ it 'takes the paging parameters too' do+ token = token_for(addressee)+ params = { posts_per_page: 2, posts_order: 'newest' }+ by_id = get_json(addressee, ticket_path, params, token: token)+ expect(get_json(addressee, number_path(ticket.number), params, token: token)).to eq(by_id)+ expect(by_id.dig('data', 'posts_total')).to eq(7)+ get_json(addressee, number_path(ticket.number), { posts_per_page: 51 }, token: token)+ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'never answers with the ticket of the same number in another project' do+ sibling_project, sibling = Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ other_project = create(:project, organisation: organisation)+ create(:project_permission, user: other, project: other_project, tickets_access: 'read_only')+ tickets = Array.new(2) { create(:ticket, project: other_project, organisation: organisation, creator: author) }+ [other_project, tickets.last]+ end+ end+ token = token_for(other)+ expect(get_json(other, number_path(1, project_id: sibling_project.id), {}, token: token).dig('data', 'id'))+ .not_to eq(ticket.id)+ expect(get_json(other, number_path(ticket.number), {}, token: token).dig('data', 'id')).to eq(ticket.id)+ get_json(other, number_path(sibling.number), {}, token: token)+ expect_not_found+ end++ it 'answers an unknown number with the not-found body' do+ get_json(other, number_path(ticket.number + 1))+ expect_not_found+ end++ %w[abc 0 -1 1.5].each do |raw|+ it "answers the malformed number #{raw.inspect} like a missing one" do+ get_json(other, number_path(raw))+ expect_not_found+ end+ end++ it 'answers an unknown project like a missing number' do+ get_json(other, number_path(ticket.number, project_id: SecureRandom.uuid))+ expect_not_found+ end++ it 'hides a project beyond the token reach, even from an account admin' do+ elsewhere = Prosopite.pause { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }+ token = token_for(admin, project_scopes: { organisation => [elsewhere] })+ get_json(admin, number_path(ticket.number), {}, token: token)+ expect_not_found+ end++ it 'hides the ticket from a member without access to its project' do+ outsider = member(tickets: nil)+ get_json(outsider, number_path(ticket.number))+ expect_not_found+ end++ it 'hides the ticket from a member who may read only the notes of its project' do+ notes_only = member(tickets: 'no_access')+ Prosopite.pause do+ ActsAsTenant.with_tenant(organisation) do+ notes_only.project_permissions.find_by!(project: project).update!(notes_access: 'read_only')+ end+ end+ get_json(notes_only, number_path(ticket.number))+ expect_not_found+ end++ it 'hides a ticket of another organisation' do+ foreign = Prosopite.pause do+ org = create(:organisation)+ ActsAsTenant.with_tenant(org) do+ create(:ticket, organisation: org, project: create(:project, organisation: org), creator: create(:user))+ end+ end+ get_json(other, number_path(foreign.number, project_id: foreign.project_id))+ expect_not_found+ end++ it 'refuses invalid paging before it looks the number up' do+ token = token_for(other)+ get_json(other, number_path(999), { posts_order: 'random' }, token: token)+ missing = [response.status, response.body]+ get_json(other, number_path(ticket.number), { posts_order: 'random' }, token: token)+ expect([response.status, response.body]).to eq(missing)+ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spec/services/tickets/reading_spec.rb b/spec/services/tickets/reading_spec.rbnew file mode 100644index 0000000..6379f9a--- /dev/null+++ b/spec/services/tickets/reading_spec.rb@@ -0,0 +1,55 @@+# frozen_string_literal: true++require 'rails_helper'++# The options of the ticket view, shared by MCP get_ticket and the REST ticket+# view. The pages themselves are pinned through both surfaces+# (get_ticket_paging_spec.rb, spec/requests/api/v1/ticket_view_spec.rb).+RSpec.describe Tickets::Reading do+ describe '.options' do+ it 'defaults to the first page of 50, oldest first' do+ options = described_class.options({})+ expect(options.to_h).to eq(posts_page: 1, posts_per_page: 50, newest: false, attachments_page: 1)+ end++ it 'reads strings as well as integers' do+ options = described_class.options({ posts_page: '2', posts_per_page: 3, posts_order: 'newest', attachments_page: ' 4 ' })+ expect(options.to_h).to eq(posts_page: 2, posts_per_page: 3, newest: true, attachments_page: 4)+ end++ it 'treats a blank value like a missing one' do+ expect(described_class.options({ posts_page: ' ', posts_order: '' }).to_h)+ .to eq(posts_page: 1, posts_per_page: 50, newest: false, attachments_page: 1)+ end++ it 'clamps posts_per_page above 50 for MCP and refuses it for REST' do+ expect(described_class.options({ posts_per_page: 51 }, over_max: :clamp).posts_per_page).to eq(50)+ expect(described_class.options({ posts_per_page: 50 }, over_max: :refuse).posts_per_page).to eq(50)+ expect { described_class.options({ posts_per_page: '51' }, over_max: :refuse) }+ .to raise_error(described_class::InvalidOption, /posts_per_page "51" \(1 to 50\)/)+ end++ {+ { posts_page: 0 } => /posts_page 0/,+ { posts_page: '100001' } => /posts_page/,+ { posts_page: 'abc' } => /posts_page "abc"/,+ { posts_page: ['1'] } => /posts_page/,+ { posts_per_page: 0 } => /posts_per_page 0/,+ { posts_order: 'random' } => /posts_order "random"/,+ { attachments_page: -1 } => /attachments_page -1/+ }.each do |args, message|+ it "refuses #{args.inspect}" do+ expect { described_class.options(args) }.to raise_error(described_class::InvalidOption, message)+ end+ end+ end++ describe '.paging_requested?' do+ it 'is switched on by any one of the four options, even empty' do+ described_class::PAGING_KEYS.each do |key|+ expect(described_class.paging_requested?(ActionController::Parameters.new(key => ''))).to be(true)+ end+ expect(described_class.paging_requested?(ActionController::Parameters.new(full_text: 'true'))).to be(false)+ end+ end+end