Files
Jaayden Halko 17a2b62205 feat: add an API to attach templates to chat projects (#30754)
Adds the API for attaching workspace templates to a chat project, on the
schema and queries in #32309. A project can attach templates, turn on a
limit that restricts its chats to them, and set a default template with
either a default preset or default parameter values. Attaching a
template never grants access to it: every reader is checked against the
template's own sharing. This PR stores and returns `limit_templates`;
#32310 enforces it.

- The limit is opt-in. `limit_templates` is off unless a request turns
it on, which is what every existing project gets.
- Templates are attached and detached one at a time with `PUT` and
`DELETE /chats/projects/{project}/templates/{template}`, so a caller
never replaces a list they can only partly see. Attaching needs project
`update` and template `use`. Detaching needs project `update` and
template `read`, and a template the caller cannot read is reported as
not found. `POST /chats/projects` accepts `template_ids`,
`limit_templates`, and `default_template` for the new project.
- `PATCH /chats/projects/{project}` sets `limit_templates` and
`default_template`, and no longer changes which templates are attached.
The default must be an attached template the caller can read, and its
preset must belong to the template's active version. Default parameter
names and values are checked against that version for templates on the
classic parameter flow; dynamic parameters are checked when a workspace
is built. Detaching the default template clears the default.
- Project responses list only the attached templates the caller can
read, as `templates`, and count the rest as `hidden_template_count`.
`default_template` is omitted when the caller cannot read it. Deleted,
deprecated, and agent-disabled templates are left out and are not
counted as hidden.
- Editing uses `chat_project:update`, which the project owner and the
project `admin` ACL role have.
- Attaching and detaching are audited as writes to the project, with the
template list before and after, including the templates attached while
creating a project. Changes to `limit_templates` and the default
template are part of the project's own audit diff.

Not included: showing which project members lack access to an attached
template, and MCP server attachments.

Stack (merge top to bottom):
- #32309
- #30754 👈
- #32310
- #30755
- #32371
- #32372
- #30756
- #32373
- #32374
- #32375
- #30898
- #32376
- #32377
- #32378
- #32379
2026-11-18 20:36:34 +07:00
..

package chattool

import (
	"bufio"
	"strings"
	"unicode"

	"github.com/coder/coder/v2/coderd/render"
	coderstrings "github.com/coder/coder/v2/coderd/util/strings"
)

// readmeInputMaxBytes caps how many README bytes are parsed so a giant README
// can't OOM coderd. It sits well above the output rune cap, so it never trims a
// real excerpt.
const readmeInputMaxBytes = 64 * 1024

// readmeText returns the README as bounded, frontmatter-stripped plain text
// truncated to maxRunes, or "" when the README is blank or conversion fails.
func readmeText(readme string, maxRunes int) string {
	// Cap the parse input first (see readmeInputMaxBytes); goldmark and the
	// tokenizer tolerate a mid-line or mid-rune cut.
	bounded := readme[:min(len(readme), readmeInputMaxBytes)]
	text, err := render.InnerTextFromMarkdown(stripReadmeFrontmatter(bounded))
	if err != nil {
		return ""
	}
	return coderstrings.Truncate(text, maxRunes, coderstrings.TruncateWithEllipsis)
}

// stripReadmeFrontmatter strips a leading frontmatter block from the README if it
// exists. An unterminated frontmatter block is treated as a regular body section.
// UTF-8 BOMs are stripped if present, and CRLF is normalized to LF. Leading
// whitespace is also stripped.
func stripReadmeFrontmatter(readme string) string {
	trimmed := strings.TrimLeftFunc(readme, func(r rune) bool {
		return unicode.IsSpace(r) || r == '\ufeff'
	})

	var out strings.Builder
	scn := bufio.NewScanner(strings.NewReader(trimmed))
	scn.Buffer(nil, readmeInputMaxBytes+1) // headroom
	var lineNumber int
	var fences int
	for scn.Scan() {
		line := scn.Text()
		lineNumber++

		// Only handle fences if we haven't already found an
		// opening and closing fence.
		if fences < 2 {
			isFence := strings.TrimRight(line, " \t\r") == "---"
			if isFence {
				fences++
				continue
			} else if lineNumber == 1 {
				// No leading fence -> no frontmatter. Return the entire document.
				return trimmed
			}
			// We are still in the frontmatter block. Skip writing this line.
			continue
		}
		_, _ = out.WriteString(line)
		_, _ = out.WriteString("\n")
	}

	// Can err if input is too big. Shouldn't happen normally.
	if scn.Err() != nil {
		return trimmed
	}

	// Scanner did not scan any lines. No frontmatter to strip.
	if lineNumber == 0 {
		return trimmed
	}

	// If we are still fenced but we reached the end of the document
	// we have an unterminated fence.
	if fences == 1 {
		return trimmed
	}
	return out.String()
}