Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: let agents read the issues in a saved view (MUL-8532) (#9855)
Jiayuan Zhang7a12304f1473
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex 5a6edcbf65..585d17dad1 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -287,6 +287,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Europ| `issue` | Créer, mettre à jour, assigner et rechercher des tâches ; gérer les commentaires, les abonnés, les étiquettes, les propriétés, les réveils, la chronologie et les exécutions || `project` | Gérer les projets et leurs ressources || `label`, `property` | Gérer les étiquettes et les propriétés personnalisées de l'espace de travail |+| `view` | Lire les vues enregistrées et lister les tâches qu'une vue affiche || `agent`, `skill`, `squad` | Gérer les agents, les skills et les squads || `autopilot` | Gérer les automatisations, les déclencheurs et l'historique des exécutions || `workspace` | Créer, consulter et changer d'espace de travail, et inviter des membres |@@ -381,6 +382,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| | `resource list/add/update/remove` | Gérer les ressources d'un projet | `--type`, `--url`, `--default-branch-hint`, `--ref`, `--local-path`, `--daemon-id`, `--execution-mode` (`in_place` / `worktree` pour un répertoire local) || `label` | `list/get/create/update/delete` | Gérer les étiquettes de l'espace de travail | `list` : `--resource-type` (`issue` ou `skill`), `--full-id` ; `create` : `--name`, `--color`, `--resource-type` (`issue` ou `skill`), `--description` || `property` | `list/get/create/update/archive/unarchive` | Gérer les propriétés personnalisées de l'espace de travail | `create` : `--name`, `--type` (`text`, `number`, `select`, `multi_select`, `date`, `checkbox`, `url`, `actor`, `multi_actor`), `--option` (répétable, types select uniquement) ; `list` : `--include-archived` ; le type ne peut plus être modifié après la création |+| `view` | `list/get/issues` | Lire les vues que vous pouvez ouvrir (les vôtres et celles partagées avec l'espace de travail) ; `issues` liste les tâches qu'une vue affiche, dans son ordre enregistré, avec tous ses filtres appliqués par le serveur. Pendant l'exécution d'un agent, les vues et les conditions « moi » sont celles du propriétaire du runtime | `<view>` accepte un ID, un préfixe d'ID ou le nom exact ; `list` : `--scope` (`workspace`, `my`, `project`), `--project`, `--full-id` ; `issues` : `--limit` (100 au maximum), `--cursor` (le `next_cursor` de la page précédente), `--today` (le jour de référence des filtres d'échéance relatifs ; aujourd'hui par défaut), `--fields` (JSON uniquement), `--full-id` || `agent` | `list/get/create/update/archive/restore` | Gérer les agents | `--name`, `--runtime-id` (obligatoire pour `create`), `--instructions`, `--conversation-starters`, `--model`, `--thinking-level`, `--custom-env` / `--custom-env-file` / `--custom-env-stdin` (`create` uniquement), `--custom-args`, `--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`, `--permission-mode`, `--visibility` (ancienne forme), `--max-concurrent-tasks` || | `copy <agent-id>` | Copier dans un nouvel agent ; l'original reste intact | `--name` (par défaut, le nom d'origine suivi de ` (copy)`), `--runtime-id` (copier vers un autre runtime exige aussi `--model`), `--no-skills` ; la configuration secrète comme `custom_env`, `mcp_config` et `runtime_config` n'est pas copiée — fournissez-la à nouveau avec les mêmes options que pour `create` || | `tasks <id>` | Afficher les exécutions d'un agent | |diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex e954191aa6..5cb2b7a330 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -287,6 +287,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `issue` | タスクの作成、更新、割り当て、検索。コメント、購読者、ラベル、プロパティ、ウェイクアップ、タイムライン、実行履歴の管理 || `project` | プロジェクトとそのリソースを管理 || `label`、`property` | ワークスペースのラベルとカスタムプロパティを管理 |+| `view` | 保存したビューを読み取り、ビューに表示されるタスクを一覧 || `agent`、`skill`、`squad` | エージェント、スキル、スクワッドを管理 || `autopilot` | オートパイロット、トリガー、実行履歴を管理 || `workspace` | ワークスペースの作成、表示、切り替えとメンバーの招待 |@@ -373,6 +374,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `resource list/add/update/remove` | プロジェクトの追加リソースを管理 | `--type`、`--url`、`--default-branch-hint`、`--ref`、`--local-path`、`--daemon-id`、`--execution-mode`(ローカルディレクトリの `in_place` / `worktree`) || `label` | `list/get/create/update/delete` | ワークスペースのラベルを管理 | `list`: `--resource-type`(`issue` または `skill`)、`--full-id`;`create`: `--name`、`--color`、`--resource-type`(`issue` または `skill`)、`--description` || `property` | `list/get/create/update/archive/unarchive` | ワークスペースのカスタムプロパティを管理 | `create`: `--name`、`--type`(`text`、`number`、`select`、`multi_select`、`date`、`checkbox`、`url`、`actor`、`multi_actor`、`multi_text`、`multi_url`)、`--option`(繰り返し可、select 系のみ);`list`: `--include-archived`;タイプは作成後に変更できません |+| `view` | `list/get/issues` | 開けるビュー(自分のものとワークスペースで共有されたもの)を読み取り、`issues` でビューに表示されるタスクを保存された並び順で一覧(保存されたフィルターはすべてサーバー側で適用)。エージェントの実行中は、ビューと「自分」の条件はランタイム所有者のものになります | `<view>` は ID、ID プレフィックス、または完全な名前を受け付けます;`list`: `--scope`(`workspace`、`my`、`project`)、`--project`、`--full-id`;`issues`: `--limit`(最大 100)、`--cursor`(前のページの `next_cursor`)、`--today`(相対的な期日フィルターの基準日、既定は今日)、`--fields`(JSON のみ)、`--full-id` || `agent` | `list/get/create/update/archive/restore` | エージェントを管理 | `--name`、`--runtime-id`(`create` では必須)、`--instructions`、`--conversation-starters`、`--model`、`--thinking-level`、`--custom-env` / `--custom-env-file` / `--custom-env-stdin`(`create` のみ)、`--custom-args`、`--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`、`--permission-mode`、`--visibility`(古い書き方)、`--max-concurrent-tasks` || | `copy <agent-id>` | 新しいエージェントとして複製。元のエージェントは変更されません | `--name`(デフォルトは元の名前 + ` (copy)`)、`--runtime-id`(別のランタイムへ複製する場合は `--model` の同時指定が必須)、`--no-skills`;`custom_env`、`mcp_config`、`runtime_config` などの機密設定は複製されないため、`create` と同じフラグで再指定してください || | `tasks <id>` | エージェントの実行を表示 | |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 1dc2613437..9d68bbe35e 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -287,6 +287,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `issue` | 태스크 생성, 업데이트, 할당, 검색. 댓글, 구독, 라벨, 속성, 깨우기, 타임라인, 실행 기록 관리 || `project` | 프로젝트와 프로젝트 리소스 관리 || `label`, `property` | 워크스페이스 라벨과 사용자 지정 속성 관리 |+| `view` | 저장된 뷰를 읽고 뷰에 보이는 태스크 나열 || `agent`, `skill`, `squad` | 에이전트, 스킬, 스쿼드 관리 || `autopilot` | 자동화, 트리거, 실행 기록 관리 || `workspace` | 워크스페이스 생성, 확인, 전환 및 멤버 초대 |@@ -373,6 +374,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `resource list/add/update/remove` | 프로젝트 추가 리소스 관리 | `--type`, `--url`, `--default-branch-hint`, `--ref`, `--local-path`, `--daemon-id`, `--execution-mode`(로컬 디렉터리의 `in_place` / `worktree`) || `label` | `list/get/create/update/delete` | 워크스페이스 라벨 관리 | `list`: `--resource-type`(`issue` 또는 `skill`), `--full-id`; `create`: `--name`, `--color`, `--resource-type`(`issue` 또는 `skill`), `--description` || `property` | `list/get/create/update/archive/unarchive` | 워크스페이스 사용자 지정 속성 관리 | `create`: `--name`, `--type`(`text`, `number`, `select`, `multi_select`, `date`, `checkbox`, `url`, `actor`, `multi_actor`, `multi_text`, `multi_url`), `--option`(반복 가능, select 유형만). `list`: `--include-archived`. 유형은 생성 후 변경 불가 |+| `view` | `list/get/issues` | 열 수 있는 뷰(내 뷰와 워크스페이스에 공유된 뷰)를 읽고, `issues`로 뷰에 보이는 태스크를 저장된 정렬 순서대로 나열(저장된 필터는 모두 서버에서 적용). 에이전트 실행 중에는 뷰와 '나' 조건이 런타임 소유자 기준 | `<view>`는 ID, ID 접두사 또는 정확한 이름을 받음. `list`: `--scope`(`workspace`, `my`, `project`), `--project`, `--full-id`. `issues`: `--limit`(최대 100), `--cursor`(이전 페이지의 `next_cursor`), `--today`(상대 마감일 필터의 기준일, 기본값은 오늘), `--fields`(JSON 전용), `--full-id` || `agent` | `list/get/create/update/archive/restore` | 에이전트 관리 | `--name`, `--runtime-id`(`create`에서 필수), `--instructions`, `--conversation-starters`, `--model`, `--thinking-level`, `--custom-env` / `--custom-env-file` / `--custom-env-stdin`(`create` 전용), `--custom-args`, `--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`, `--permission-mode`, `--visibility`(예전 방식), `--max-concurrent-tasks` || | `copy <agent-id>` | 원래 에이전트에 영향 없이 새 에이전트로 복사 | `--name`(기본값은 원래 이름 + ` (copy)`), `--runtime-id`(다른 런타임으로 복사할 때 `--model`도 필수), `--no-skills`. `custom_env`, `mcp_config`, `runtime_config` 같은 기밀 설정은 복사되지 않으며 `create`와 같은 flag로 다시 제공해야 함 || | `tasks <id>` | 에이전트 실행 확인 | |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex a8a58fcaea..34e3e37a09 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -303,6 +303,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Europ| `project` | Manage projects, their resources, and the workflow they use || `workflow` | Manage issue workflows: statuses and who handles each one || `label`, `property` | Manage workspace labels and custom properties |+| `view` | Read saved issue views and list the issues a view shows || `agent`, `skill`, `squad` | Manage agents, skills, and squads || `autopilot` | Manage automations, triggers, and run history || `workspace` | Create, view, and switch workspaces, and invite members |@@ -406,6 +407,7 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| | `handoff set <workflow> <status-key>` | Set one step's handler, instructions, and next/back status; unchanged fields are kept | `--handler` (`none`, `project_lead`, `creator`, or a member/agent/squad name or UUID), `--instructions` / `--instructions-file`, `--next`, `--back`, `--copy-for-project` || `label` | `list/get/create/update/delete` | Manage workspace labels | `list`: `--resource-type` (`issue` or `skill`), `--full-id`; `create`: `--name`, `--color`, `--resource-type` (`issue` or `skill`), `--description` || `property` | `list/get/create/update/archive/unarchive` | Manage workspace custom properties | `create`: `--name`, `--type` (`text`, `number`, `select`, `multi_select`, `date`, `checkbox`, `url`, `actor`, `multi_actor`, `multi_text`, `multi_url`), `--option` (repeatable, select types only); `list`: `--include-archived`; the type cannot be changed after creation |+| `view` | `list/get/issues` | Read the saved views you can open (your own and workspace-shared ones); `issues` lists what a view shows, in its saved order, with every saved filter applied by the server. Inside an agent run, the views and any "my" conditions are the runtime owner's | `<view>` accepts an ID, ID prefix, or exact name; `list`: `--scope` (`workspace`, `my`, `project`), `--project`, `--full-id`; `issues`: `--limit` (at most 100), `--cursor` (the previous page's `next_cursor`), `--today` (the day relative due-date filters resolve against; default today), `--fields` (JSON only), `--full-id` || `agent` | `list/get/create/update/archive/restore` | Manage agents | `--name`, `--runtime-id` (required for `create`), `--instructions`, `--conversation-starters`, `--model`, `--thinking-level`, `--custom-env` / `--custom-env-file` / `--custom-env-stdin` (`create` only), `--custom-args`, `--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`, `--permission-mode`, `--visibility` (older form), `--max-concurrent-tasks` || | `copy <agent-id>` | Copy into a new agent; the original is untouched | `--name` (defaults to the original name plus ` (copy)`), `--runtime-id` (copying to another runtime also requires `--model`), `--no-skills`; secret configuration such as `custom_env`, `mcp_config`, and `runtime_config` is not copied — re-provide it with the same flags as `create` || | `tasks <id>` | View an agent's runs | |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex e691925b80..fea6165982 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -288,6 +288,7 @@ multica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1" --timezone Asia/| `project` | 管理项目、项目资源和项目使用的工作流 || `workflow` | 管理工作流:状态以及每个状态交给谁处理 || `label`、`property` | 管理工作区标签和自定义属性 |+| `view` | 读取保存的视图,列出视图里的任务 || `agent`、`skill`、`squad` | 管理智能体、skill 和小队 || `autopilot` | 管理自动化、触发器和运行历史 || `workspace` | 创建、查看、切换工作区和邀请成员 |@@ -383,6 +384,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `handoff set <workflow> <status-key>` | 设置单个步骤的处理人、说明和下一步/退回状态,未指定的字段保持不变 | `--handler`(`none`、`project_lead`、`creator`,或成员/智能体/小队的名称或 UUID)、`--instructions` / `--instructions-file`、`--next`、`--back`、`--copy-for-project` || `label` | `list/get/create/update/delete` | 管理工作区标签 | `list`:`--resource-type`(`issue` 或 `skill`)、`--full-id`;`create`:`--name`、`--color`、`--resource-type`(`issue` 或 `skill`)、`--description` || `property` | `list/get/create/update/archive/unarchive` | 管理工作区自定义属性 | `create`:`--name`、`--type`(`text`、`number`、`select`、`multi_select`、`date`、`checkbox`、`url`、`actor`、`multi_actor`、`multi_text`、`multi_url`)、`--option`(可重复,仅 select 类型);`list`:`--include-archived`;类型创建后不可修改 |+| `view` | `list/get/issues` | 读取你能打开的视图(自己的和工作区共享的);`issues` 按视图保存的排序列出视图里的任务,视图保存的全部筛选条件都由服务端执行。在智能体运行中,看到的视图和其中「我的」条件都属于运行时的所有者 | `<view>` 接受 ID、ID 前缀或完整名称;`list`:`--scope`(`workspace`、`my`、`project`)、`--project`、`--full-id`;`issues`:`--limit`(最多 100)、`--cursor`(上一页的 `next_cursor`)、`--today`(相对到期日筛选按哪一天计算,默认今天)、`--fields`(仅 JSON)、`--full-id` || `agent` | `list/get/create/update/archive/restore` | 管理智能体 | `--name`、`--runtime-id`(`create` 必填)、`--instructions`、`--conversation-starters`、`--model`、`--thinking-level`、`--custom-env` / `--custom-env-file` / `--custom-env-stdin`(仅 `create`)、`--custom-args`、`--mcp-config` / `--mcp-config-file` / `--mcp-config-stdin`、`--permission-mode`、`--visibility`(旧写法)、`--max-concurrent-tasks` || | `copy <agent-id>` | 复制为新智能体,原智能体不受影响 | `--name`(默认为原名加 ` (copy)`)、`--runtime-id`(复制到其他运行时时必须同时指定 `--model`)、`--no-skills`;`custom_env`、`mcp_config`、`runtime_config` 等机密配置不会复制,需用与 `create` 相同的 flag 重新提供 || | `tasks <id>` | 查看智能体的运行 | |diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex ea9a043664..5eb61ded1e 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -12,6 +12,7 @@ import ("path/filepath""reflect""regexp"+ "slices""sort""strconv""strings"@@ -912,23 +913,12 @@ func runIssueList(cmd *cobra.Command, _ []string) error {params.Set("direction", d)}- var fields []string- if v, _ := cmd.Flags().GetString("fields"); v != "" {- valid := make(map[string]bool, len(validIssueFields))- for _, f := range validIssueFields {- valid[f] = true- }- keepsProperties := false- for _, f := range strings.Split(v, ",") {- f = strings.TrimSpace(f)- if !valid[f] {- return fmt.Errorf("invalid --fields value %q; valid values: %s", f, strings.Join(validIssueFields, ", "))- }- if f == "properties" {- keepsProperties = true- }- fields = append(fields, f)- }+ fields, err := parseIssueFieldsFlag(cmd)+ if err != nil {+ return err+ }+ if len(fields) > 0 {+ keepsProperties := slices.Contains(fields, "properties")// --fields without `properties` deletes the very key// --resolve-properties rewrites, so the pair would either cost two// requests for output nobody sees or leave the flag silently doing@@ -1003,6 +993,33 @@ func runIssueList(cmd *cobra.Command, _ []string) error {}fullID, _ := cmd.Flags().GetBool("full-id")+ printIssueListTable(ctx, client, issuesRaw, fullID)+ // Page footer on stderr so stdout stays a plain table. It speaks whenever+ // there is more or the page was offset, and stays silent for a short+ // first page. "of N" appears only while total is trusted, so the line+ // never claims a page is the whole list beside a pointer to the next one.+ switch {+ case returned == 0 && offset > 0:+ if totalTrusted {+ fmt.Fprintf(os.Stderr, "No issues at --offset %d (%d total).\n", offset, int(total))+ } else {+ fmt.Fprintf(os.Stderr, "No issues at --offset %d.\n", offset)+ }+ case hasMore || offset > 0:+ line := fmt.Sprintf("Showing issues %d-%d.", offset+1, offset+returned)+ if totalTrusted {+ line = fmt.Sprintf("Showing %d-%d of %d issues.", offset+1, offset+returned, int(total))+ }+ if hasMore {+ line += fmt.Sprintf(" Next page: --offset %d", offset+returned)+ }+ fmt.Fprintln(os.Stderr, line)+ }+ return nil+}++// printIssueListTable prints issue rows in the `issue list` table layout.+func printIssueListTable(ctx context.Context, client *cli.APIClient, issuesRaw []any, fullID bool) {headers := []string{"KEY", "TITLE", "STATUS", "PRIORITY", "ASSIGNEE", "START DATE", "DUE DATE"}if fullID {headers = []string{"KEY", "ID", "TITLE", "STATUS", "PRIORITY", "ASSIGNEE", "START DATE", "DUE DATE"}@@ -1047,28 +1064,6 @@ func runIssueList(cmd *cobra.Command, _ []string) error {rows = append(rows, row)}cli.PrintTable(os.Stdout, headers, rows)- // Page footer on stderr so stdout stays a plain table. It speaks whenever- // there is more or the page was offset, and stays silent for a short- // first page. "of N" appears only while total is trusted, so the line- // never claims a page is the whole list beside a pointer to the next one.- switch {- case returned == 0 && offset > 0:- if totalTrusted {- fmt.Fprintf(os.Stderr, "No issues at --offset %d (%d total).\n", offset, int(total))- } else {- fmt.Fprintf(os.Stderr, "No issues at --offset %d.\n", offset)- }- case hasMore || offset > 0:- line := fmt.Sprintf("Showing issues %d-%d.", offset+1, offset+returned)- if totalTrusted {- line = fmt.Sprintf("Showing %d-%d of %d issues.", offset+1, offset+returned, int(total))- }- if hasMore {- line += fmt.Sprintf(" Next page: --offset %d", offset+returned)- }- fmt.Fprintln(os.Stderr, line)- }- return nil}func runIssuePullRequests(cmd *cobra.Command, args []string) error {@@ -3677,6 +3672,24 @@ func formatAssignee(issue map[string]any, actors actorDisplayLookup) string {return actors.actor(aType, aID)}+// parseIssueFieldsFlag validates --fields against validIssueFields; nil+// means the flag was not given.+func parseIssueFieldsFlag(cmd *cobra.Command) ([]string, error) {+ v, _ := cmd.Flags().GetString("fields")+ if v == "" {+ return nil, nil+ }+ var fields []string+ for _, f := range strings.Split(v, ",") {+ f = strings.TrimSpace(f)+ if !slices.Contains(validIssueFields, f) {+ return nil, fmt.Errorf("invalid --fields value %q; valid values: %s", f, strings.Join(validIssueFields, ", "))+ }+ fields = append(fields, f)+ }+ return fields, nil+}+// filterIssueFields keeps only the requested top-level keys on each issue,// dropping everything else — including description, which makes up most of// a typical issue payload. Opt-in via --fields on JSON output only.diff --git a/server/cmd/multica/cmd_view.go b/server/cmd/multica/cmd_view.gonew file mode 100644index 0000000000..b41155378b--- /dev/null+++ b/server/cmd/multica/cmd_view.go@@ -0,0 +1,327 @@+package main++import (+ "context"+ "fmt"+ "net/url"+ "os"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++// View commands — read the saved issue views a member can open, and the+// issues each one lists.++const viewIssuesMaxPageSize = 100++var viewCmd = &cobra.Command{+ Use: "view",+ Short: "Read saved issue views and the issues they list",+ Long: `Read saved issue views and the issues they list.++A view is the caller's own or a workspace-shared saved filter. Inside an agent+run the caller is the runtime owner, so the views listed and any "my" scope or+"assigned to me" condition are the runtime owner's.`,+}++var viewListCmd = &cobra.Command{+ Use: "list",+ Short: "List the saved views you can open",+ RunE: runViewList,+}++var viewGetCmd = &cobra.Command{+ Use: "get <view>",+ Short: "Get a view's definition",+ Long: "Get a view's definition. <view> is a view ID, ID prefix, or exact name (case-insensitive).",+ Args: exactArgs(1),+ RunE: runViewGet,+}++var viewIssuesCmd = &cobra.Command{+ Use: "issues <view>",+ Short: "List the issues a view shows",+ Long: `List the issues a view shows, in the view's saved order, with every filter the+view saves applied by the server. <view> is a view ID, ID prefix, or exact name+(case-insensitive).++Pages hold at most 100 issues. While --output json reports has_more, pass its+next_cursor to --cursor for the next page; total is reported on the first page.`,+ Args: exactArgs(1),+ RunE: runViewIssues,+}++func init() {+ viewCmd.AddCommand(viewListCmd)+ viewCmd.AddCommand(viewGetCmd)+ viewCmd.AddCommand(viewIssuesCmd)++ viewListCmd.Flags().String("scope", "", "Only views of this scope: workspace, my, or project")+ viewListCmd.Flags().String("project", "", "Only views of this project (ID or ID prefix)")+ viewListCmd.Flags().String("output", "table", "Output format: table or json")+ viewListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")++ viewGetCmd.Flags().String("output", "json", "Output format: table or json")++ viewIssuesCmd.Flags().Int("limit", 50, fmt.Sprintf("Page size, 1 to %d", viewIssuesMaxPageSize))+ viewIssuesCmd.Flags().String("cursor", "", "Continue from the next_cursor of the previous page")+ viewIssuesCmd.Flags().String("today", "", "Calendar day (YYYY-MM-DD) that relative due-date filters resolve against (default: today in local time)")+ viewIssuesCmd.Flags().String("output", "table", "Output format: table or json")+ viewIssuesCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")+ viewIssuesCmd.Flags().String("fields", "", "JSON output only: comma-separated list of issue fields to include (e.g. id,identifier,title,status). Valid fields: "+strings.Join(validIssueFields, ", "))+}++func listIssueViews(ctx context.Context, client *cli.APIClient) ([]map[string]any, error) {+ if client.WorkspaceID == "" {+ return nil, fmt.Errorf("workspace_id is required to list views")+ }+ var raw []any+ if err := client.GetJSON(ctx, "/api/issue-views?scope_type=all", &raw); err != nil {+ return nil, fmt.Errorf("list views: %w", err)+ }+ views := make([]map[string]any, 0, len(raw))+ for _, item := range raw {+ if view, ok := item.(map[string]any); ok {+ views = append(views, view)+ }+ }+ return views, nil+}++// resolveIssueView finds a view by full ID, exact name (case-insensitive),+// or ID prefix, in that order.+func resolveIssueView(ctx context.Context, client *cli.APIClient, input string) (map[string]any, error) {+ ref := strings.TrimSpace(input)+ if ref == "" {+ return nil, fmt.Errorf("view is required")+ }+ if uuidRegexp.MatchString(ref) {+ var view map[string]any+ if err := client.GetJSON(ctx, "/api/issue-views/"+url.PathEscape(ref), &view); err != nil {+ return nil, err+ }+ return view, nil+ }+ views, err := listIssueViews(ctx, client)+ if err != nil {+ return nil, err+ }+ var byName []map[string]any+ for _, view := range views {+ if strings.EqualFold(strVal(view, "name"), ref) {+ byName = append(byName, view)+ }+ }+ if len(byName) == 1 {+ return byName[0], nil+ }+ if len(byName) > 1 {+ matches := make([]idCandidate, 0, len(byName))+ for _, view := range byName {+ matches = append(matches, idCandidate{ID: strVal(view, "id")})+ }+ return nil, fmt.Errorf("more than one view is named %q; pass its ID:\n%s", ref, joinCandidateIDs(matches))+ }+ prefix, err := normalizeUUIDPrefix(ref)+ if err != nil {+ return nil, fmt.Errorf("no view named %q; run `multica view list`", ref)+ }+ var matches []idCandidate+ var found map[string]any+ for _, view := range views {+ if strings.HasPrefix(compactUUID(strVal(view, "id")), prefix) {+ matches = append(matches, idCandidate{ID: strVal(view, "id")})+ found = view+ }+ }+ switch len(matches) {+ case 0:+ return nil, fmt.Errorf("no view found matching %q; run `multica view list --full-id`", ref)+ case 1:+ return found, nil+ default:+ return nil, ambiguousIDPrefixError("view", ref, matches)+ }+}++func joinCandidateIDs(matches []idCandidate) string {+ lines := make([]string, len(matches))+ for i, m := range matches {+ lines[i] = " " + m.ID+ }+ return strings.Join(lines, "\n")+}++// viewScopeLabel renders a view's scope as one table cell, e.g. "workspace",+// "workspace (agents)", "my (assigned)", "project 1a2b3c4d".+func viewScopeLabel(view map[string]any, fullID bool) string {+ label := strVal(view, "scope_type")+ if label == "project" {+ label += " " + displayID(strVal(view, "scope_id"), fullID)+ }+ if variant := strVal(view, "scope_variant"); variant != "" {+ label += " (" + variant + ")"+ }+ return label+}++func runViewList(cmd *cobra.Command, _ []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ scope, _ := cmd.Flags().GetString("scope")+ if scope != "" && scope != "workspace" && scope != "my" && scope != "project" {+ return fmt.Errorf("invalid --scope %q; valid values: workspace, my, project", scope)+ }+ projectID := ""+ if v, _ := cmd.Flags().GetString("project"); v != "" {+ if scope != "" && scope != "project" {+ return fmt.Errorf("--project lists project views; it cannot be combined with --scope %s", scope)+ }+ project, err := resolveProjectID(ctx, client, v)+ if err != nil {+ return err+ }+ projectID = project.ID+ }++ views, err := listIssueViews(ctx, client)+ if err != nil {+ return err+ }+ shown := make([]map[string]any, 0, len(views))+ for _, view := range views {+ if scope != "" && strVal(view, "scope_type") != scope {+ continue+ }+ if projectID != "" && strVal(view, "scope_id") != projectID {+ continue+ }+ shown = append(shown, view)+ }++ if output, _ := cmd.Flags().GetString("output"); output == "json" {+ return cli.PrintJSON(os.Stdout, shown)+ }+ fullID, _ := cmd.Flags().GetBool("full-id")+ actors := loadActorDisplayLookup(ctx, client)+ headers := []string{"ID", "NAME", "SCOPE", "VISIBILITY", "OWNER"}+ rows := make([][]string, 0, len(shown))+ for _, view := range shown {+ rows = append(rows, []string{+ displayID(strVal(view, "id"), fullID),+ strVal(view, "name"),+ viewScopeLabel(view, fullID),+ strVal(view, "visibility"),+ actors.actor("member", strVal(view, "owner_id")),+ })+ }+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}++func runViewGet(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ view, err := resolveIssueView(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve view: %w", err)+ }+ if output, _ := cmd.Flags().GetString("output"); output == "table" {+ actors := loadActorDisplayLookup(ctx, client)+ cli.PrintTable(os.Stdout, []string{"ID", "NAME", "SCOPE", "VISIBILITY", "OWNER"}, [][]string{{+ strVal(view, "id"),+ strVal(view, "name"),+ viewScopeLabel(view, true),+ strVal(view, "visibility"),+ actors.actor("member", strVal(view, "owner_id")),+ }})+ return nil+ }+ return cli.PrintJSON(os.Stdout, view)+}++func runViewIssues(cmd *cobra.Command, args []string) error {+ limit, _ := cmd.Flags().GetInt("limit")+ if limit < 1 || limit > viewIssuesMaxPageSize {+ return fmt.Errorf("--limit must be between 1 and %d; use --cursor to page through more", viewIssuesMaxPageSize)+ }+ today, _ := cmd.Flags().GetString("today")+ if today == "" {+ today = time.Now().Format(time.DateOnly)+ } else if _, err := time.Parse(time.DateOnly, today); err != nil {+ return fmt.Errorf("invalid --today %q; use YYYY-MM-DD", today)+ }+ fields, err := parseIssueFieldsFlag(cmd)+ if err != nil {+ return err+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ view, err := resolveIssueView(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve view: %w", err)+ }++ params := url.Values{}+ params.Set("limit", fmt.Sprintf("%d", limit))+ params.Set("today", today)+ if cursor, _ := cmd.Flags().GetString("cursor"); cursor != "" {+ params.Set("cursor", cursor)+ }+ var result map[string]any+ path := "/api/issue-views/" + url.PathEscape(strVal(view, "id")) + "/issues?" + params.Encode()+ if err := client.GetJSON(ctx, path, &result); err != nil {+ return fmt.Errorf("list view issues: %w", err)+ }+ issuesRaw, _ := result["issues"].([]any)+ hasMore, _ := result["has_more"].(bool)+ nextCursor := strVal(result, "next_cursor")++ if output, _ := cmd.Flags().GetString("output"); output == "json" {+ if len(fields) > 0 {+ filterIssueFields(issuesRaw, fields)+ }+ wrapped := map[string]any{+ "view": map[string]any{"id": strVal(view, "id"), "name": strVal(view, "name")},+ "issues": issuesRaw,+ "limit": limit,+ "has_more": hasMore,+ "next_cursor": result["next_cursor"],+ }+ if total, ok := result["total"]; ok {+ wrapped["total"] = total+ }+ return cli.PrintJSON(os.Stdout, wrapped)+ }++ fullID, _ := cmd.Flags().GetBool("full-id")+ printIssueListTable(ctx, client, issuesRaw, fullID)+ if hasMore && nextCursor != "" {+ line := fmt.Sprintf("Showing %d issues.", len(issuesRaw))+ if total, ok := result["total"].(float64); ok {+ line = fmt.Sprintf("Showing %d of %d issues.", len(issuesRaw), int(total))+ }+ fmt.Fprintf(os.Stderr, "%s Next page: --cursor %s\n", line, nextCursor)+ }+ return nil+}diff --git a/server/cmd/multica/cmd_view_test.go b/server/cmd/multica/cmd_view_test.gonew file mode 100644index 0000000000..290d8f59dc--- /dev/null+++ b/server/cmd/multica/cmd_view_test.go@@ -0,0 +1,196 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync"+ "testing"++ "github.com/spf13/cobra"+)++const (+ testViewBugsUUID = "6a000000-0000-0000-0000-000000000001"+ testViewBugsTwoUUID = "6b000000-0000-0000-0000-000000000002"+ testViewMineUUID = "6c000000-0000-0000-0000-000000000003"+ testViewProjectUUID = "77777777-7777-7777-7777-777777777777"+)++// viewTestServer serves three views — "Bugs" (workspace), "Mine" (my) and a+// second "bugs" (project) — and records each issues request's query.+func viewTestServer(t *testing.T) *[]url.Values {+ t.Helper()+ views := []any{+ map[string]any{"id": testViewBugsUUID, "name": "Bugs", "scope_type": "workspace", "scope_id": nil, "visibility": "workspace", "owner_id": "u1"},+ map[string]any{"id": testViewMineUUID, "name": "Mine", "scope_type": "my", "scope_id": nil, "scope_variant": "assigned", "visibility": "private", "owner_id": "u1"},+ map[string]any{"id": testViewBugsTwoUUID, "name": "bugs", "scope_type": "project", "scope_id": testViewProjectUUID, "visibility": "workspace", "owner_id": "u1"},+ }+ var mu sync.Mutex+ var issueQueries []url.Values+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issue-views" && r.URL.Query().Get("scope_type") == "all":+ _ = json.NewEncoder(w).Encode(views)+ case r.Method == http.MethodGet && r.URL.Path == "/api/issue-views/"+testViewMineUUID:+ _ = json.NewEncoder(w).Encode(views[1])+ case r.Method == http.MethodGet && r.URL.Path == "/api/issue-views/"+testViewMineUUID+"/issues":+ mu.Lock()+ issueQueries = append(issueQueries, r.URL.Query())+ mu.Unlock()+ response := map[string]any{+ "issues": []any{+ map[string]any{"id": "i1", "identifier": "MUL-1", "title": "First", "status": "todo", "description": "long"},+ },+ "has_more": true,+ "next_cursor": "c2",+ }+ if r.URL.Query().Get("cursor") == "" {+ response["total"] = 2+ }+ _ = json.NewEncoder(w).Encode(response)+ default:+ t.Errorf("unexpected request %s %s", r.Method, r.URL.String())+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ t.Cleanup(srv.Close)+ setCLITestServerEnv(t, srv.URL)+ return &issueQueries+}++func TestResolveIssueViewByIDNameAndPrefix(t *testing.T) {+ viewTestServer(t)+ client, err := newAPIClient(&cobra.Command{})+ if err != nil {+ t.Fatal(err)+ }+ for input, want := range map[string]string{+ testViewMineUUID: testViewMineUUID,+ "mine": testViewMineUUID,+ "6c00": testViewMineUUID,+ } {+ view, err := resolveIssueView(t.Context(), client, input)+ if err != nil {+ t.Fatalf("resolveIssueView(%q): %v", input, err)+ }+ if strVal(view, "id") != want {+ t.Errorf("resolveIssueView(%q) = %s, want %s", input, strVal(view, "id"), want)+ }+ }+ if _, err := resolveIssueView(t.Context(), client, "BUGS"); err == nil || !strings.Contains(err.Error(), "more than one view") {+ t.Fatalf("duplicate name: err = %v", err)+ }+ if _, err := resolveIssueView(t.Context(), client, "nope"); err == nil {+ t.Fatal("unknown name: want an error")+ }+}++func newViewIssuesTestCmd(t *testing.T, flags map[string]string) *cobra.Command {+ t.Helper()+ cmd := &cobra.Command{Use: "issues"}+ cmd.Flags().Int("limit", 50, "")+ cmd.Flags().String("cursor", "", "")+ cmd.Flags().String("today", "", "")+ cmd.Flags().String("output", "table", "")+ cmd.Flags().Bool("full-id", false, "")+ cmd.Flags().String("fields", "", "")+ for name, value := range flags {+ if err := cmd.Flags().Set(name, value); err != nil {+ t.Fatal(err)+ }+ }+ return cmd+}++func TestViewIssuesRequestsThePageAndWrapsJSON(t *testing.T) {+ queries := viewTestServer(t)+ cmd := newViewIssuesTestCmd(t, map[string]string{+ "output": "json", "limit": "10", "today": "2026-03-11", "fields": "identifier,title",+ })+ out, err := captureStdout(t, func() error { return runViewIssues(cmd, []string{"Mine"}) })+ if err != nil {+ t.Fatalf("run: %v", err)+ }+ if len(*queries) != 1 {+ t.Fatalf("issues requests = %d, want 1", len(*queries))+ }+ query := (*queries)[0]+ if query.Get("limit") != "10" || query.Get("today") != "2026-03-11" || query.Has("cursor") {+ t.Fatalf("issues query = %v", query)+ }+ var got map[string]any+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("decode output: %v\n%s", err, out)+ }+ if view, _ := got["view"].(map[string]any); strVal(view, "id") != testViewMineUUID || strVal(view, "name") != "Mine" {+ t.Fatalf("view = %v", got["view"])+ }+ if got["total"] != float64(2) || got["has_more"] != true || got["next_cursor"] != "c2" || got["limit"] != float64(10) {+ t.Fatalf("page meta = %v", got)+ }+ issues, _ := got["issues"].([]any)+ issue, _ := issues[0].(map[string]any)+ if len(issue) != 2 || issue["identifier"] != "MUL-1" || issue["title"] != "First" {+ t.Fatalf("issue after --fields = %v", issue)+ }+}++func TestViewIssuesPassesTheCursorAndOmitsTotalAfterTheFirstPage(t *testing.T) {+ queries := viewTestServer(t)+ cmd := newViewIssuesTestCmd(t, map[string]string{"output": "json", "cursor": "c2"})+ out, err := captureStdout(t, func() error { return runViewIssues(cmd, []string{testViewMineUUID}) })+ if err != nil {+ t.Fatalf("run: %v", err)+ }+ if got := (*queries)[0]; got.Get("cursor") != "c2" || got.Get("today") == "" {+ t.Fatalf("issues query = %v", got)+ }+ var got map[string]any+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatal(err)+ }+ if _, ok := got["total"]; ok {+ t.Fatalf("total on a continuation page: %v", got)+ }+}++func TestViewIssuesRejectsBadFlagsBeforeAnyRequest(t *testing.T) {+ queries := viewTestServer(t)+ for name, flags := range map[string]map[string]string{+ "limit too large": {"limit": "101"},+ "limit zero": {"limit": "0"},+ "bad today": {"today": "03/11/2026"},+ "bad field": {"fields": "assignee"},+ } {+ if err := runViewIssues(newViewIssuesTestCmd(t, flags), []string{"Mine"}); err == nil {+ t.Errorf("%s: want an error", name)+ }+ }+ if len(*queries) != 0 {+ t.Fatalf("issues requests = %d, want 0", len(*queries))+ }+}++func TestViewListFiltersByScope(t *testing.T) {+ viewTestServer(t)+ cmd := &cobra.Command{Use: "list"}+ cmd.Flags().String("scope", "", "")+ cmd.Flags().String("project", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().Bool("full-id", false, "")+ _ = cmd.Flags().Set("scope", "my")+ out, err := captureStdout(t, func() error { return runViewList(cmd, nil) })+ if err != nil {+ t.Fatalf("run: %v", err)+ }+ var views []map[string]any+ if err := json.Unmarshal([]byte(out), &views); err != nil {+ t.Fatal(err)+ }+ if len(views) != 1 || strVal(views[0], "id") != testViewMineUUID {+ t.Fatalf("views = %v", views)+ }+}diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 62276b7e4e..f5f1089c51 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -53,6 +53,7 @@ func init() {workflowCmd.GroupID = groupCorelabelCmd.GroupID = groupCorepropertyCmd.GroupID = groupCore+ viewCmd.GroupID = groupCoreagentCmd.GroupID = groupCoreautopilotCmd.GroupID = groupCoreworkspaceCmd.GroupID = groupCore@@ -80,6 +81,7 @@ func init() {rootCmd.AddCommand(workflowCmd)rootCmd.AddCommand(labelCmd)rootCmd.AddCommand(propertyCmd)+ rootCmd.AddCommand(viewCmd)rootCmd.AddCommand(agentCmd)rootCmd.AddCommand(autopilotCmd)rootCmd.AddCommand(workspaceCmd)diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f50159461f..31dae0118b 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2305,6 +2305,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/", h.CreateIssueView)r.Route("/{id}", func(r chi.Router) {r.Get("/", h.GetIssueViewByID)+ r.Get("/issues", h.ListIssueViewIssues)r.Patch("/", h.UpdateIssueView)r.Delete("/", h.DeleteIssueView)})diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.goindex 5ec8fef955..11137420ef 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -235,18 +235,28 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "database is unavailable")return}- baseHandler := hvar request issueTableRowsRequestif !decodeIssueTableJSON(w, r, &request) {return}+ response, ok := h.queryIssueTableRows(w, r, request)+ if !ok {+ return+ }+ writeJSON(w, http.StatusOK, response)+}++// queryIssueTableRows runs one table rows request. On failure it has already+// written the error response and returns ok=false.+func (h *Handler) queryIssueTableRows(w http.ResponseWriter, r *http.Request, request issueTableRowsRequest) (issueTableRowsResponse, bool) {+ baseHandler := hr, cancel := withIssueTableQueryTimeout(r)defer cancel()snapshot, tx, err := h.beginIssueTableSnapshot(r.Context())if err != nil {slog.Warn("ListIssueTableRows snapshot failed", append(logger.RequestAttrs(r), "error", err)...)writeIssueTableQueryFailure(w, r, "failed to start table query")- return+ return issueTableRowsResponse{}, false}committed := falsedefer func() {@@ -257,22 +267,22 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {h = snapshotlimit, cursor, ok := normalizeIssueTablePage(w, request.Page)if !ok {- return+ return issueTableRowsResponse{}, false}groupKey, ok := normalizeIssueTableGroupKey(w, request.Group, request.GroupKey)if !ok {- return+ return issueTableRowsResponse{}, false}if !request.Hierarchy.Enabled && request.ParentID != nil {writeError(w, http.StatusBadRequest, "parent_id requires hierarchy.enabled=true")- return+ return issueTableRowsResponse{}, false}compiled, ok := h.compileIssueTableQuery(w, r, request.Query)if !ok {- return+ return issueTableRowsResponse{}, false}if !issueTableCursorMatches(w, cursor, compiled.fingerprint, groupKey, request.ParentID) {- return+ return issueTableRowsResponse{}, false}branchIdentity := issueTableGroupIdentity(request.Group) + ":hierarchy=" + strconv.FormatBool(request.Hierarchy.Enabled)if cursor != nil && cursor.BranchIdentity != branchIdentity {@@ -280,11 +290,11 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {"error": "cursor_query_mismatch","message": "cursor does not belong to this table branch",})- return+ return issueTableRowsResponse{}, false}group, ok := h.resolveIssueTableGroup(w, r, compiled.workspaceID, request.Group, true)if !ok {- return+ return issueTableRowsResponse{}, false}args := append([]any(nil), compiled.args...)addArg := func(value any) string {@@ -299,7 +309,7 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {addArg,)if !ok {- return+ return issueTableRowsResponse{}, false}predicateKey := ""if groupKey != nil {@@ -307,7 +317,7 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {}groupPredicate, ok := group.predicate(w, predicateKey, addArg)if !ok {- return+ return issueTableRowsResponse{}, false}branchPredicate := "TRUE"if request.Hierarchy.Enabled {@@ -320,7 +330,7 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {parentUUID, err := util.ParseUUID(*request.ParentID)if err != nil {writeError(w, http.StatusBadRequest, "invalid parent_id")- return+ return issueTableRowsResponse{}, false}parentRef := addArg(parentUUID)branchPredicate = fmt.Sprintf("i.parent_issue_id = %s::uuid AND EXISTS (SELECT 1 FROM membership parent WHERE parent.id = %s::uuid)", parentRef, parentRef)@@ -328,7 +338,7 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {}cursorPredicate, ok := resolvedSort.cursorPredicate(w, cursor, addArg)if !ok {- return+ return issueTableRowsResponse{}, false}limitRef := addArg(limit + 1)@@ -402,7 +412,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,if err != nil {slog.Warn("ListIssueTableRows query failed", append(logger.RequestAttrs(r), "error", err)...)writeIssueTableQueryFailure(w, r, "failed to list table rows")- return+ return issueTableRowsResponse{}, false}defer rows.Close()@@ -443,13 +453,13 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,&row.sortKey,); err != nil {writeIssueTableQueryFailure(w, r, "failed to list table rows")- return+ return issueTableRowsResponse{}, false}scanned = append(scanned, row)}if err := rows.Err(); err != nil {writeIssueTableQueryFailure(w, r, "failed to list table rows")- return+ return issueTableRowsResponse{}, false}rows.Close()@@ -461,7 +471,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,if err := h.DB.QueryRow(r.Context(), fmt.Sprintf("SELECT COUNT(*)::bigint FROM issue i WHERE %s", compiled.where), compiled.args...).Scan(&total); err != nil {slog.Warn("ListIssueTableRows total count failed", append(logger.RequestAttrs(r), "error", err)...)writeIssueTableQueryFailure(w, r, "failed to count table rows")- return+ return issueTableRowsResponse{}, false}}@@ -495,7 +505,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,if err := tx.Commit(r.Context()); err != nil {slog.Warn("ListIssueTableRows snapshot commit failed", append(logger.RequestAttrs(r), "error", err)...)writeIssueTableQueryFailure(w, r, "failed to finish table query")- return+ return issueTableRowsResponse{}, false}committed = true@@ -534,5 +544,5 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,BranchTotal: int64(len(responseRows)),NextCursor: nextCursor,}- writeJSON(w, http.StatusOK, response)+ return response, true}diff --git a/server/internal/handler/issue_view_issues.go b/server/internal/handler/issue_view_issues.gonew file mode 100644index 0000000000..bfde1366a7--- /dev/null+++ b/server/internal/handler/issue_view_issues.go@@ -0,0 +1,593 @@+package handler++import (+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "strconv"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// A saved view's `query` is written by the web client. The translation below+// mirrors viewSidebarRequest in packages/core/issues/sidebar-list.ts (with the+// sanitizing of baselineFromQuery and sanitizeAdvancedFilter), plus what the+// opened view drops on top of it (use-issue-surface-controller.ts): conditions+// on a scope-fixed field or on a property that is no longer active, and a sort+// on such a property. Values the client would drop are dropped here too;+// values the client would send but the table query rejects are left for the+// table query to reject.++// issueViewFilterDimensions are the client's negatable dimensions in its+// canonical order, with their table query field.+var issueViewFilterDimensions = []struct {+ dimension string+ field string+}{+ {"status", "statuses"},+ {"priority", "priorities"},+ {"assignee", "assignees"},+ {"creator", "creators"},+ {"project", "project_ids"},+ {"projectStatus", "project_statuses"},+ {"label", "label_ids"},+ {"relation", "relations"},+ {"dueDate", "due_dates"},+}++var issueViewSorts = []string{+ "position", "status", "priority", "title", "created_at", "updated_at",+ "last_activity", "start_date", "due_date",+}++var issueViewPropertyFilterOps = []string{"contains", "gt", "gte", "lt", "lte", "before", "after"}++var issueViewActorTypes = []string{"member", "agent", "squad"}++var errIssueViewScopeUnlistable = errors.New("this view's scope cannot be listed")++func issueViewFilterField(dimension string) (string, bool) {+ for _, d := range issueViewFilterDimensions {+ if d.dimension == dimension {+ return d.field, true+ }+ }+ return "", false+}++func decodeIssueViewObject(raw []byte) map[string]json.RawMessage {+ var object map[string]json.RawMessage+ if json.Unmarshal(raw, &object) != nil {+ return nil+ }+ return object+}++func issueViewBool(raw json.RawMessage) bool {+ var value bool+ return json.Unmarshal(raw, &value) == nil && value+}++func issueViewString(raw json.RawMessage) (string, bool) {+ var value string+ if json.Unmarshal(raw, &value) != nil {+ return "", false+ }+ return value, true+}++func issueViewArray(raw json.RawMessage) []json.RawMessage {+ var values []json.RawMessage+ if json.Unmarshal(raw, &values) != nil {+ return nil+ }+ return values+}++// issueViewStrings keeps the string members of a JSON array that pass keep.+func issueViewStrings(raw json.RawMessage, keep func(string) bool) []string {+ var result []string+ for _, member := range issueViewArray(raw) {+ if value, ok := issueViewString(member); ok && keep(value) {+ result = append(result, value)+ }+ }+ return result+}++func issueViewUniqueStrings(values []string) []string {+ seen := make(map[string]struct{}, len(values))+ result := make([]string, 0, len(values))+ for _, value := range values {+ if _, ok := seen[value]; ok {+ continue+ }+ seen[value] = struct{}{}+ result = append(result, value)+ }+ return result+}++func issueViewOneOf(allowed []string) func(string) bool {+ return func(value string) bool { return issueTableContainsString(allowed, value) }+}++func issueViewNonEmpty(value string) bool { return value != "" }++func issueViewAny(string) bool { return true }++// issueViewActors keeps array members that are objects with a string id.+func issueViewActors(raw json.RawMessage) []issueTableActorRef {+ var result []issueTableActorRef+ for _, member := range issueViewArray(raw) {+ object := decodeIssueViewObject(member)+ if object == nil {+ continue+ }+ id, ok := issueViewString(object["id"])+ if !ok {+ continue+ }+ actorType, _ := issueViewString(object["type"])+ result = append(result, issueTableActorRef{Type: actorType, ID: id})+ }+ return result+}++// issueViewPropertyMember returns one property filter member in table query+// form plus its dedup key: a string, or an operator object with a known op.+func issueViewPropertyMember(raw json.RawMessage, allowEmpty bool) (json.RawMessage, string, bool) {+ if value, ok := issueViewString(raw); ok {+ if value == "" && !allowEmpty {+ return nil, "", false+ }+ encoded, _ := json.Marshal(value)+ return encoded, value, true+ }+ object := decodeIssueViewObject(raw)+ if object == nil {+ return nil, "", false+ }+ op, opOK := issueViewString(object["op"])+ value, valueOK := issueViewString(object["value"])+ if !opOK || !valueOK || !issueTableContainsString(issueViewPropertyFilterOps, op) {+ return nil, "", false+ }+ encoded, _ := json.Marshal(map[string]string{"op": op, "value": value})+ return encoded, op + "\x00" + value, true+}++func issueViewPropertyFilters(raw json.RawMessage, activeProperties map[string]bool) map[string][]json.RawMessage {+ object := decodeIssueViewObject(raw)+ result := make(map[string][]json.RawMessage, len(object))+ for propertyID, membersRaw := range object {+ if !activeProperties[propertyID] {+ continue+ }+ var members []json.RawMessage+ for _, member := range issueViewArray(membersRaw) {+ if encoded, _, ok := issueViewPropertyMember(member, true); ok {+ members = append(members, encoded)+ }+ }+ if len(members) > 0 {+ result[propertyID] = members+ }+ }+ return result+}++// issueViewConditionValues keeps the advanced condition values the client+// can represent for a built-in dimension.+func issueViewConditionValues(dimension string, values []string) []string {+ switch dimension {+ case "priority":+ return issueViewKeep(values, issueViewOneOf(validIssuePriorities))+ case "projectStatus":+ return issueViewKeep(values, issueViewOneOf(validProjectStatuses))+ case "relation":+ return issueViewKeep(values, issueViewOneOf(issueTableRelations))+ case "dueDate":+ return issueViewKeep(values, issueViewOneOf(issueTableDueDates))+ case "assignee", "creator":+ return issueViewKeep(values, func(value string) bool {+ if value == issueTableFilterNoneValue {+ return dimension == "assignee"+ }+ parts := strings.Split(value, ":")+ return len(parts) >= 2 && parts[0] != "" && parts[1] != "" &&+ issueTableContainsString(issueViewActorTypes, parts[0])+ })+ default:+ return issueViewKeep(values, issueViewNonEmpty)+ }+}++func issueViewKeep(values []string, keep func(string) bool) []string {+ result := make([]string, 0, len(values))+ for _, value := range values {+ if keep(value) {+ result = append(result, value)+ }+ }+ return result+}++// issueViewAdvancedNode sanitizes, prunes and converts one advanced filter+// node: the root group is depth 0 and may hold groups, a nested group holds+// conditions only. Nodes the client would drop, conditions on a field drop+// reports (by its client field name), conditions without values and groups+// left empty return ok=false.+func issueViewAdvancedNode(raw json.RawMessage, depth int, drop func(field string) bool) (issueTableFilterNode, bool) {+ object := decodeIssueViewObject(raw)+ if object == nil {+ return issueTableFilterNode{}, false+ }+ nodeType, _ := issueViewString(object["type"])+ switch nodeType {+ case "group":+ var children []json.RawMessage+ if depth > 1 || json.Unmarshal(object["children"], &children) != nil || children == nil {+ return issueTableFilterNode{}, false+ }+ match := "all"+ if value, _ := issueViewString(object["match"]); value == "any" {+ match = "any"+ }+ group := issueTableFilterNode{Match: match}+ for _, child := range children {+ if node, ok := issueViewAdvancedNode(child, depth+1, drop); ok {+ group.Children = append(group.Children, node)+ }+ }+ return group, len(group.Children) > 0+ case "condition":+ negate := issueViewBool(object["negated"])+ field, _ := issueViewString(object["field"])+ if drop(field) {+ return issueTableFilterNode{}, false+ }+ if len(field) > len(issueTableFilterPropertyPrefix) && strings.HasPrefix(field, issueTableFilterPropertyPrefix) {+ seen := map[string]struct{}{}+ var values []json.RawMessage+ for _, member := range issueViewArray(object["values"]) {+ encoded, key, ok := issueViewPropertyMember(member, false)+ if !ok {+ continue+ }+ if _, dup := seen[key]; dup {+ continue+ }+ seen[key] = struct{}{}+ values = append(values, encoded)+ }+ return issueTableFilterNode{Field: field, Negate: negate, Values: values}, len(values) > 0+ }+ tableField, ok := issueViewFilterField(field)+ if !ok {+ return issueTableFilterNode{}, false+ }+ strs := issueViewConditionValues(field, issueViewUniqueStrings(issueViewStrings(object["values"], issueViewAny)))+ values := make([]json.RawMessage, len(strs))+ for i, value := range strs {+ values[i], _ = json.Marshal(value)+ }+ return issueTableFilterNode{Field: tableField, Negate: negate, Values: values}, len(values) > 0+ default:+ return issueTableFilterNode{}, false+ }+}++func issueViewAdvancedUsesField(node issueTableFilterNode, field string) bool {+ if !node.isGroup() {+ return node.Field == field+ }+ for _, child := range node.Children {+ if issueViewAdvancedUsesField(child, field) {+ return true+ }+ }+ return false+}++func issueViewTableScope(view db.IssueView) (issueTableScope, error) {+ var assigneeTypes []string+ switch view.ScopeVariant.String {+ case "members":+ assigneeTypes = []string{"member"}+ case "agents":+ assigneeTypes = []string{"agent", "squad"}+ }+ switch view.ScopeType {+ case "workspace":+ return issueTableScope{Kind: "workspace", AssigneeTypes: assigneeTypes}, nil+ case "project":+ if !view.ScopeID.Valid {+ return issueTableScope{}, errIssueViewScopeUnlistable+ }+ return issueTableScope{Kind: "project", ProjectID: uuidToString(view.ScopeID), AssigneeTypes: assigneeTypes}, nil+ case "my":+ relation := "any"+ if view.ScopeVariant.Valid {+ relation = view.ScopeVariant.String+ }+ switch relation {+ case "assigned", "created", "involved", "any":+ return issueTableScope{Kind: "my", Relation: relation}, nil+ }+ }+ return issueTableScope{}, errIssueViewScopeUnlistable+}++func issueViewPropertyIDOfField(field string) (string, bool) {+ if len(field) > len(issueTableFilterPropertyPrefix) && strings.HasPrefix(field, issueTableFilterPropertyPrefix) {+ return field[len(issueTableFilterPropertyPrefix):], true+ }+ return "", false+}++// issueViewReferencedPropertyIDs lists the properties a view's filters and+// sort name, for resolving which of them are still active.+func issueViewReferencedPropertyIDs(view db.IssueView) []string {+ query := decodeIssueViewObject(view.Query)+ var ids []string+ for propertyID := range decodeIssueViewObject(query["propertyFilters"]) {+ ids = append(ids, propertyID)+ }+ // Same depth bound as issueViewAdvancedNode: conditions sit at most two+ // levels below the root group.+ var walk func(raw json.RawMessage, depth int)+ walk = func(raw json.RawMessage, depth int) {+ object := decodeIssueViewObject(raw)+ if object == nil || depth > 2 {+ return+ }+ field, _ := issueViewString(object["field"])+ if id, ok := issueViewPropertyIDOfField(field); ok {+ ids = append(ids, id)+ }+ for _, child := range issueViewArray(object["children"]) {+ walk(child, depth+1)+ }+ }+ walk(query["advancedFilter"], 0)+ sortBy, _ := issueViewString(decodeIssueViewObject(view.Display)["sortBy"])+ if id, ok := issueViewPropertyIDOfField(sortBy); ok {+ ids = append(ids, id)+ }+ return issueViewUniqueStrings(ids)+}++// issueViewTableQuery is the table query listing what a saved view shows.+// today is the viewer's calendar day, used only by due-date conditions.+// activeProperties holds the ids of the workspace's active properties the+// view references; filters and sorts on any other property are dropped.+func issueViewTableQuery(view db.IssueView, today string, activeProperties map[string]bool) (issueTableQuerySpec, error) {+ scope, err := issueViewTableScope(view)+ if err != nil {+ return issueTableQuerySpec{}, err+ }+ query := decodeIssueViewObject(view.Query)+ display := decodeIssueViewObject(view.Display)++ statuses := issueViewStrings(query["statusFilters"], issueViewNonEmpty)+ priorities := issueViewStrings(query["priorityFilters"], issueViewOneOf(validIssuePriorities))+ assignees := issueViewActors(query["assigneeFilters"])+ includeNoAssignee := issueViewBool(query["includeNoAssignee"])+ creators := issueViewActors(query["creatorFilters"])+ projectIDs := issueViewStrings(query["projectFilters"], issueViewAny)+ includeNoProject := issueViewBool(query["includeNoProject"])+ projectStatuses := issueViewStrings(query["projectStatusFilters"], issueViewOneOf(validProjectStatuses))+ labelIDs := issueViewStrings(query["labelFilters"], issueViewAny)+ relations := issueViewStrings(query["relationFilters"], issueViewOneOf(issueTableRelations))+ dueDates := issueViewUniqueStrings(issueViewStrings(query["dueDateFilters"], issueViewOneOf(issueTableDueDates)))+ negated := issueViewStrings(query["negatedFilters"], func(dimension string) bool {+ _, ok := issueViewFilterField(dimension)+ return ok+ })+ // Same as the page the view opens: a project view drops the project+ // dimension, a "my" view the viewer-relation one.+ fixedField := ""+ switch scope.Kind {+ case "project":+ projectIDs, includeNoProject = nil, false+ fixedField = "project"+ case "my":+ relations = nil+ fixedField = "relation"+ }+ dropCondition := func(field string) bool {+ if id, ok := issueViewPropertyIDOfField(field); ok {+ return !activeProperties[id]+ }+ return field == fixedField+ }++ hasSelection := map[string]bool{+ "status": len(statuses) > 0,+ "priority": len(priorities) > 0,+ "assignee": len(assignees) > 0 || includeNoAssignee,+ "creator": len(creators) > 0,+ "project": len(projectIDs) > 0 || includeNoProject,+ "projectStatus": len(projectStatuses) > 0,+ "label": len(labelIDs) > 0,+ "relation": len(relations) > 0,+ "dueDate": len(dueDates) > 0,+ }+ var negate []string+ for _, d := range issueViewFilterDimensions {+ if hasSelection[d.dimension] && issueTableContainsString(negated, d.dimension) {+ negate = append(negate, d.field)+ }+ }++ filters := issueTableFiltersRequest{+ Statuses: statuses,+ Priorities: priorities,+ IncludeNoAssignee: includeNoAssignee,+ Creators: creators,+ ProjectIDs: projectIDs,+ IncludeNoProject: includeNoProject,+ ProjectStatuses: projectStatuses,+ LabelIDs: labelIDs,+ Relations: relations,+ DueDates: dueDates,+ Negate: negate,+ WorkingOnly: issueViewBool(query["agentRunningFilter"]),+ }+ // An explicitly empty assignee list means "match none" to the table query.+ if len(assignees) > 0 {+ filters.Assignees = assignees+ }+ usesDueDates := len(dueDates) > 0+ if advanced, ok := issueViewAdvancedNode(query["advancedFilter"], 0, dropCondition); ok && advanced.isGroup() {+ filters.Advanced = &advanced+ usesDueDates = usesDueDates || issueViewAdvancedUsesField(advanced, "due_dates")+ }+ if usesDueDates {+ filters.Today = today+ }+ if properties := issueViewPropertyFilters(query["propertyFilters"], activeProperties); len(properties) > 0 {+ filters.Properties = properties+ }+ showSubIssues := true+ if raw, ok := display["showSubIssues"]; ok {+ var value bool+ if json.Unmarshal(raw, &value) == nil && !value {+ showSubIssues = false+ }+ }+ filters.IncludeSubIssues = &showSubIssues++ sort := issueTableSortRequest{Field: "position", Direction: "asc"}+ if field, ok := issueViewString(display["sortBy"]); ok {+ if id, isProperty := issueViewPropertyIDOfField(field); isProperty {+ if activeProperties[id] {+ sort.Field = field+ }+ } else if issueTableContainsString(issueViewSorts, field) {+ sort.Field = field+ }+ }+ if direction, _ := issueViewString(display["sortDirection"]); direction == "desc" {+ sort.Direction = "desc"+ }++ return issueTableQuerySpec{Scope: scope, Filters: filters, Sort: sort}, nil+}++type issueViewIssuesResponse struct {+ Issues []IssueResponse `json:"issues"`+ // Total counts every issue the view shows; only the first page carries it.+ Total *int64 `json:"total,omitempty"`+ NextCursor *string `json:"next_cursor"`+ HasMore bool `json:"has_more"`+}++// activeIssueViewProperties resolves which properties the view references+// still exist, unarchived, in the view's workspace.+func (h *Handler) activeIssueViewProperties(w http.ResponseWriter, r *http.Request, view db.IssueView) (map[string]bool, bool) {+ active := map[string]bool{}+ for _, id := range issueViewReferencedPropertyIDs(view) {+ propertyUUID, err := util.ParseUUID(id)+ if err != nil {+ continue+ }+ property, err := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{+ ID: propertyUUID,+ WorkspaceID: view.WorkspaceID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ continue+ }+ if err != nil {+ slog.Warn("resolve view property failed", append(logger.RequestAttrs(r), "error", err)...)+ writeIssueTableQueryFailure(w, r, "failed to resolve view properties")+ return nil, false+ }+ if !property.ArchivedAt.Valid {+ active[id] = true+ }+ }+ return active, true+}++// ListIssueViewIssues lists the issues a saved view shows, in the view's+// saved order, under the caller's identity: "my" scopes and viewer relations+// resolve against the requesting user.+func (h *Handler) ListIssueViewIssues(w http.ResponseWriter, r *http.Request) {+ if h.DB == nil {+ writeError(w, http.StatusInternalServerError, "database is unavailable")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ view, _, ok := h.loadIssueViewForUser(w, r, userID)+ if !ok {+ return+ }++ params := r.URL.Query()+ today := time.Now().UTC().Format(time.DateOnly)+ if raw := params.Get("today"); raw != "" {+ if _, ok := parseIssueTableToday(raw); !ok {+ writeError(w, http.StatusBadRequest, "today must be a YYYY-MM-DD date")+ return+ }+ today = raw+ }+ limit := issueTableDefaultPageSize+ if raw := params.Get("limit"); raw != "" {+ parsed, err := strconv.Atoi(raw)+ if err != nil || parsed < 1 || parsed > issueTableMaxPageSize {+ writeError(w, http.StatusBadRequest, fmt.Sprintf("limit must be between 1 and %d", issueTableMaxPageSize))+ return+ }+ limit = parsed+ }+ page := issueTablePageRequest{Limit: limit}+ if raw := params.Get("cursor"); raw != "" {+ page.Cursor = &raw+ }++ activeProperties, ok := h.activeIssueViewProperties(w, r, view)+ if !ok {+ return+ }+ spec, err := issueViewTableQuery(view, today, activeProperties)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ rows, ok := h.queryIssueTableRows(w, r, issueTableRowsRequest{+ Query: spec,+ Group: issueTableGroupSpec{Kind: "none"},+ Page: page,+ })+ if !ok {+ return+ }++ response := issueViewIssuesResponse{+ Issues: make([]IssueResponse, len(rows.Rows)),+ NextCursor: rows.NextCursor,+ HasMore: rows.NextCursor != nil,+ }+ for i, row := range rows.Rows {+ response.Issues[i] = row.Issue+ }+ if page.Cursor == nil {+ total := rows.Total+ response.Total = &total+ }+ writeJSON(w, http.StatusOK, response)+}diff --git a/server/internal/handler/issue_view_issues_test.go b/server/internal/handler/issue_view_issues_test.gonew file mode 100644index 0000000000..6f891db64f--- /dev/null+++ b/server/internal/handler/issue_view_issues_test.go@@ -0,0 +1,391 @@+package handler++import (+ "encoding/json"+ "fmt"+ "net/http"+ "reflect"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func issueViewForQueryTest(t *testing.T, scopeType, scopeVariant string, scopeID string, query, display map[string]any) db.IssueView {+ t.Helper()+ view := db.IssueView{ScopeType: scopeType}+ if scopeVariant != "" {+ view.ScopeVariant = pgtype.Text{String: scopeVariant, Valid: true}+ }+ if scopeID != "" {+ view.ScopeID = parseUUID(scopeID)+ }+ var err error+ if view.Query, err = json.Marshal(query); err != nil {+ t.Fatal(err)+ }+ if view.Display, err = json.Marshal(display); err != nil {+ t.Fatal(err)+ }+ return view+}++// assertIssueViewJSON compares a value with the expected JSON object by+// meaning, so field order and omitted empties do not matter.+func assertIssueViewJSON(t *testing.T, name string, got any, want string) {+ t.Helper()+ gotRaw, err := json.Marshal(got)+ if err != nil {+ t.Fatal(err)+ }+ var gotValue, wantValue any+ if err := json.Unmarshal(gotRaw, &gotValue); err != nil {+ t.Fatal(err)+ }+ if err := json.Unmarshal([]byte(want), &wantValue); err != nil {+ t.Fatalf("%s: bad expectation: %v", name, err)+ }+ if !reflect.DeepEqual(gotValue, wantValue) {+ t.Fatalf("%s:\n got %s\n want %s", name, gotRaw, want)+ }+}++const issueViewTestToday = "2026-03-11"++var issueViewTestActiveProperties = map[string]bool{"p1": true, "p2": true}++func TestIssueViewTableQueryCarriesFiltersVariantAndOrdering(t *testing.T) {+ spec, err := issueViewTableQuery(issueViewForQueryTest(t, "workspace", "agents", "",+ map[string]any{"statusFilters": []string{"todo"}, "labelFilters": []string{"l1"}, "priorityFilters": []string{"bogus"}},+ map[string]any{"sortBy": "due_date", "sortDirection": "desc", "showSubIssues": false},+ ), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ assertIssueViewJSON(t, "spec", spec, `{+ "scope": {"kind": "workspace", "assignee_types": ["agent", "squad"]},+ "filters": {"statuses": ["todo"], "label_ids": ["l1"], "include_sub_issues": false},+ "sort": {"field": "due_date", "direction": "desc"}+ }`)+}++func TestIssueViewTableQueryKeepsEveryViewCondition(t *testing.T) {+ filters := func(query map[string]any) issueTableFiltersRequest {+ t.Helper()+ spec, err := issueViewTableQuery(issueViewForQueryTest(t, "workspace", "", "", query, map[string]any{}), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ return spec.Filters+ }+ cases := []struct {+ name string+ query map[string]any+ want string+ }{+ {"relations", map[string]any{"relationFilters": []string{"assigned", "bogus"}},+ `{"relations": ["assigned"], "include_sub_issues": true}`},+ {"negation", map[string]any{"statusFilters": []string{"done"}, "negatedFilters": []string{"status", "bogus"}},+ `{"statuses": ["done"], "negate": ["statuses"], "include_sub_issues": true}`},+ {"due dates need the viewer's day", map[string]any{"dueDateFilters": []string{"overdue", "overdue"}},+ `{"due_dates": ["overdue"], "today": "2026-03-11", "include_sub_issues": true}`},+ {"project statuses", map[string]any{"projectStatusFilters": []string{"completed", "bogus"}},+ `{"project_statuses": ["completed"], "include_sub_issues": true}`},+ {"actors and no-assignee", map[string]any{+ "assigneeFilters": []any{map[string]any{"type": "agent", "id": "a1"}, "junk"},+ "includeNoAssignee": true,+ "creatorFilters": []any{map[string]any{"type": "member", "id": "m1"}},+ }, `{"assignees": [{"type": "agent", "id": "a1"}], "include_no_assignee": true,+ "creators": [{"type": "member", "id": "m1"}], "include_sub_issues": true}`},+ {"properties keep strings and known operators", map[string]any{"propertyFilters": map[string]any{+ "p1": []any{"opt", map[string]any{"op": "gte", "value": "3"}, map[string]any{"op": "bogus", "value": "x"}},+ "p2": []any{},+ }}, `{"properties": {"p1": ["opt", {"op": "gte", "value": "3"}]}, "include_sub_issues": true}`},+ {"agent running", map[string]any{"agentRunningFilter": true},+ `{"working_only": true, "include_sub_issues": true}`},+ {"advanced tree", map[string]any{"advancedFilter": map[string]any{+ "type": "group", "id": "root", "match": "any",+ "children": []any{+ map[string]any{"type": "condition", "id": "c1", "field": "priority", "negated": false, "values": []string{"urgent", "bogus"}},+ map[string]any{"type": "group", "id": "g1", "match": "all", "children": []any{+ map[string]any{"type": "condition", "id": "c2", "field": "assignee", "negated": true, "values": []string{"none", "agent:a1", "robot:x"}},+ map[string]any{"type": "condition", "id": "c3", "field": "label", "values": []string{}},+ }},+ map[string]any{"type": "group", "id": "empty", "children": []any{}},+ },+ }}, `{"advanced": {"match": "any", "children": [+ {"field": "priorities", "values": ["urgent"]},+ {"match": "all", "children": [{"field": "assignees", "negate": true, "values": ["none", "agent:a1"]}]}+ ]}, "include_sub_issues": true}`},+ {"advanced due date needs the viewer's day", map[string]any{"advancedFilter": map[string]any{+ "type": "group", "match": "all",+ "children": []any{map[string]any{"type": "condition", "field": "dueDate", "values": []string{"today"}}},+ }}, `{"advanced": {"match": "all", "children": [{"field": "due_dates", "values": ["today"]}]},+ "today": "2026-03-11", "include_sub_issues": true}`},+ {"advanced property condition", map[string]any{"advancedFilter": map[string]any{+ "type": "group", "match": "all",+ "children": []any{map[string]any{"type": "condition", "field": "property:p1", "values": []any{"", "a", "a", map[string]any{"op": "contains", "value": "x"}}}},+ }}, `{"advanced": {"match": "all", "children": [{"field": "property:p1", "values": ["a", {"op": "contains", "value": "x"}]}]},+ "include_sub_issues": true}`},+ {"an empty tree constrains nothing", map[string]any{"advancedFilter": map[string]any{+ "type": "group", "match": "all", "children": []any{map[string]any{"type": "condition", "field": "status", "values": []string{}}},+ }}, `{"include_sub_issues": true}`},+ {"is-not without a selection is no condition", map[string]any{"negatedFilters": []string{"status"}},+ `{"include_sub_issues": true}`},+ }+ for _, tc := range cases {+ assertIssueViewJSON(t, tc.name, filters(tc.query), tc.want)+ }+}++func TestIssueViewTableQueryScopesLikeTheViewPage(t *testing.T) {+ scope := func(scopeType, variant, scopeID string) (issueTableScope, error) {+ spec, err := issueViewTableQuery(issueViewForQueryTest(t, scopeType, variant, scopeID, map[string]any{}, map[string]any{}), issueViewTestToday, issueViewTestActiveProperties)+ return spec.Scope, err+ }+ projectID := "11111111-1111-1111-1111-111111111111"+ for _, tc := range []struct {+ name, scopeType, variant, scopeID, want string+ }{+ {"project", "project", "", projectID, `{"kind": "project", "project_id": "` + projectID + `"}`},+ {"project members", "project", "members", projectID, `{"kind": "project", "project_id": "` + projectID + `", "assignee_types": ["member"]}`},+ {"my created", "my", "created", "", `{"kind": "my", "relation": "created"}`},+ {"my without variant", "my", "", "", `{"kind": "my", "relation": "any"}`},+ } {+ got, err := scope(tc.scopeType, tc.variant, tc.scopeID)+ if err != nil {+ t.Fatalf("%s: %v", tc.name, err)+ }+ assertIssueViewJSON(t, tc.name, got, tc.want)+ }+ if _, err := scope("project", "", ""); err == nil {+ t.Fatal("project view without a project: want an error")+ }+ if _, err := scope("team", "", ""); err == nil {+ t.Fatal("unknown scope: want an error")+ }+}++func TestIssueViewTableQueryDropsTheDimensionTheScopeFixes(t *testing.T) {+ project, err := issueViewTableQuery(issueViewForQueryTest(t, "project", "", "11111111-1111-1111-1111-111111111111",+ map[string]any{"projectFilters": []string{"p2"}, "includeNoProject": true, "negatedFilters": []string{"project"}}, map[string]any{},+ ), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ assertIssueViewJSON(t, "project view", project.Filters, `{"include_sub_issues": true}`)+ mine, err := issueViewTableQuery(issueViewForQueryTest(t, "my", "assigned", "",+ map[string]any{"relationFilters": []string{"created"}, "negatedFilters": []string{"relation"}}, map[string]any{},+ ), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ assertIssueViewJSON(t, "my view", mine.Filters, `{"include_sub_issues": true}`)++ advanced := func(field string) map[string]any {+ return map[string]any{"advancedFilter": map[string]any{"type": "group", "match": "all", "children": []any{+ map[string]any{"type": "condition", "field": field, "values": []string{"x"}},+ map[string]any{"type": "condition", "field": "label", "values": []string{"l1"}},+ }}}+ }+ project, err = issueViewTableQuery(issueViewForQueryTest(t, "project", "", "11111111-1111-1111-1111-111111111111",+ advanced("project"), map[string]any{}), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ assertIssueViewJSON(t, "project view tree", project.Filters,+ `{"advanced": {"match": "all", "children": [{"field": "label_ids", "values": ["l1"]}]}, "include_sub_issues": true}`)+ mine, err = issueViewTableQuery(issueViewForQueryTest(t, "my", "assigned", "",+ advanced("relation"), map[string]any{}), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ assertIssueViewJSON(t, "my view tree", mine.Filters,+ `{"advanced": {"match": "all", "children": [{"field": "label_ids", "values": ["l1"]}]}, "include_sub_issues": true}`)+}++func TestIssueViewTableQueryDropsInactiveProperties(t *testing.T) {+ view := issueViewForQueryTest(t, "workspace", "", "", map[string]any{+ "propertyFilters": map[string]any{"p1": []string{"a"}, "gone": []string{"b"}},+ "advancedFilter": map[string]any{"type": "group", "match": "any", "children": []any{+ map[string]any{"type": "condition", "field": "property:gone", "values": []string{"c"}},+ map[string]any{"type": "group", "match": "all", "children": []any{+ map[string]any{"type": "condition", "field": "property:gone", "values": []string{"d"}},+ }},+ map[string]any{"type": "condition", "field": "property:p1", "values": []string{"e"}},+ }},+ }, map[string]any{"sortBy": "property:gone", "sortDirection": "desc"})+ if got := issueViewReferencedPropertyIDs(view); len(got) != 2 {+ t.Fatalf("referenced properties = %v, want p1 and gone", got)+ }+ spec, err := issueViewTableQuery(view, issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ assertIssueViewJSON(t, "filters", spec.Filters, `{+ "properties": {"p1": ["a"]},+ "advanced": {"match": "any", "children": [{"field": "property:p1", "values": ["e"]}]},+ "include_sub_issues": true+ }`)+ assertIssueViewJSON(t, "sort", spec.Sort, `{"field": "position", "direction": "desc"}`)+}++func TestIssueViewTableQuerySort(t *testing.T) {+ sort := func(display map[string]any) issueTableSortRequest {+ spec, err := issueViewTableQuery(issueViewForQueryTest(t, "workspace", "", "", map[string]any{}, display), issueViewTestToday, issueViewTestActiveProperties)+ if err != nil {+ t.Fatal(err)+ }+ return spec.Sort+ }+ assertIssueViewJSON(t, "default", sort(map[string]any{}), `{"field": "position", "direction": "asc"}`)+ assertIssueViewJSON(t, "unknown field", sort(map[string]any{"sortBy": "bogus", "sortDirection": "sideways"}), `{"field": "position", "direction": "asc"}`)+ assertIssueViewJSON(t, "property", sort(map[string]any{"sortBy": "property:p1", "sortDirection": "desc"}), `{"field": "property:p1", "direction": "desc"}`)+}++func listIssueViewIssuesForTest(t *testing.T, userID, viewID, query string) *testutil.Response {+ t.Helper()+ path := "/api/issue-views/" + viewID + "/issues"+ if query != "" {+ path += "?" + query+ }+ req := newRequest(http.MethodGet, path, nil)+ req.Header.Set("X-User-ID", userID)+ return testutil.Call(t, testHandler.ListIssueViewIssues, withURLParam(req, "id", viewID))+}++func issueViewIssueTitles(response issueViewIssuesResponse) []string {+ titles := make([]string, len(response.Issues))+ for i, issue := range response.Issues {+ titles[i] = issue.Title+ }+ return titles+}++func TestListIssueViewIssues(t *testing.T) {+ suffix := time.Now().UnixNano()+ project := dbfx.Project(t, fmt.Sprintf("view issues %d", suffix))+ title := func(name string) string { return fmt.Sprintf("%s view issues %d", name, suffix) }+ dbfx.Issue(t, title("a urgent todo"), testutil.Cols{"project_id": project, "priority": "urgent", "due_date": "2026-01-01"})+ dbfx.Issue(t, title("b urgent done"), testutil.Cols{"project_id": project, "priority": "urgent", "status": "done"})+ dbfx.Issue(t, title("c low todo"), testutil.Cols{"project_id": project, "priority": "low"})++ newView := func(visibility string, query map[string]any) string {+ t.Helper()+ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": fmt.Sprintf("view issues %d", suffix),+ "scope_type": "project",+ "scope_id": project,+ "visibility": visibility,+ "query": query,+ "display": map[string]any{"sortBy": "title", "sortDirection": "asc"},+ })+ if code != http.StatusCreated {+ t.Fatalf("create view: %d %s", code, body)+ }+ return view.ID+ }++ urgent := newView("workspace", map[string]any{"priorityFilters": []string{"urgent"}})+ var first issueViewIssuesResponse+ listIssueViewIssuesForTest(t, testUserID, urgent, "limit=1").Want(http.StatusOK).JSON(&first)+ if got := issueViewIssueTitles(first); !reflect.DeepEqual(got, []string{title("a urgent todo")}) {+ t.Fatalf("first page = %v", got)+ }+ if first.Total == nil || *first.Total != 2 || !first.HasMore || first.NextCursor == nil {+ t.Fatalf("first page meta: total=%v has_more=%v cursor=%v", first.Total, first.HasMore, first.NextCursor)+ }+ var second issueViewIssuesResponse+ listIssueViewIssuesForTest(t, testUserID, urgent, "limit=1&cursor="+*first.NextCursor).Want(http.StatusOK).JSON(&second)+ if got := issueViewIssueTitles(second); !reflect.DeepEqual(got, []string{title("b urgent done")}) {+ t.Fatalf("second page = %v", got)+ }+ if second.Total != nil || second.HasMore || second.NextCursor != nil {+ t.Fatalf("second page meta: total=%v has_more=%v cursor=%v", second.Total, second.HasMore, second.NextCursor)+ }++ notDone := newView("workspace", map[string]any{+ "priorityFilters": []string{"urgent"}, "statusFilters": []string{"done"}, "negatedFilters": []string{"status"},+ })+ var negated issueViewIssuesResponse+ listIssueViewIssuesForTest(t, testUserID, notDone, "").Want(http.StatusOK).JSON(&negated)+ if got := issueViewIssueTitles(negated); !reflect.DeepEqual(got, []string{title("a urgent todo")}) {+ t.Fatalf("urgent and not done = %v", got)+ }++ overdue := newView("workspace", map[string]any{"dueDateFilters": []string{"overdue"}})+ var late, early issueViewIssuesResponse+ listIssueViewIssuesForTest(t, testUserID, overdue, "today=2026-03-11").Want(http.StatusOK).JSON(&late)+ if got := issueViewIssueTitles(late); !reflect.DeepEqual(got, []string{title("a urgent todo")}) {+ t.Fatalf("overdue on 2026-03-11 = %v", got)+ }+ listIssueViewIssuesForTest(t, testUserID, overdue, "today=2025-12-01").Want(http.StatusOK).JSON(&early)+ if len(early.Issues) != 0 {+ t.Fatalf("overdue on 2025-12-01 = %v", issueViewIssueTitles(early))+ }++ listIssueViewIssuesForTest(t, testUserID, urgent, "today=03/11/2026").Want(http.StatusBadRequest)+ listIssueViewIssuesForTest(t, testUserID, urgent, "limit=0").Want(http.StatusBadRequest)+ listIssueViewIssuesForTest(t, testUserID, urgent, "limit=101").Want(http.StatusBadRequest)+}++func TestListIssueViewIssuesDropsArchivedPropertyConditions(t *testing.T) {+ for _, advanced := range []bool{false, true} {+ name := "flat"+ if advanced {+ name = "advanced"+ }+ t.Run(name, func(t *testing.T) {+ suffix := time.Now().UnixNano()+ project := dbfx.Project(t, fmt.Sprintf("view archived property %s %d", name, suffix))+ property := createTestProperty(t, map[string]any{"name": fmt.Sprintf("Sev %s %d", name, suffix%1e9), "type": "text"})+ critical := dbfx.Issue(t, "view property critical", testutil.Cols{"project_id": project})+ dbfx.Issue(t, "view property unset", testutil.Cols{"project_id": project})+ if w := setIssuePropertyRaw(t, critical, property.ID, "critical"); w.Code != http.StatusOK {+ t.Fatalf("set property: %d %s", w.Code, w.Body.String())+ }+ query := map[string]any{"propertyFilters": map[string]any{property.ID: []string{"critical"}}}+ if advanced {+ query = map[string]any{"advancedFilter": map[string]any{"type": "group", "match": "all", "children": []any{+ map[string]any{"type": "condition", "field": "property:" + property.ID, "values": []string{"critical"}},+ }}}+ }+ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": fmt.Sprintf("view archived property %s %d", name, suffix), "scope_type": "project", "scope_id": project,+ "query": query, "display": map[string]any{"sortBy": "property:" + property.ID},+ })+ if code != http.StatusCreated {+ t.Fatalf("create view: %d %s", code, body)+ }++ var before, after issueViewIssuesResponse+ listIssueViewIssuesForTest(t, testUserID, view.ID, "").Want(http.StatusOK).JSON(&before)+ if len(before.Issues) != 1 {+ t.Fatalf("active property: got %v, want only the critical issue", issueViewIssueTitles(before))+ }+ req := withURLParam(newRequest(http.MethodPatch, "/api/properties/"+property.ID, map[string]any{"archived": true}), "id", property.ID)+ testutil.Call(t, testHandler.UpdateProperty, req).Want(http.StatusOK)+ listIssueViewIssuesForTest(t, testUserID, view.ID, "").Want(http.StatusOK).JSON(&after)+ if len(after.Issues) != 2 {+ t.Fatalf("archived property: got %v, want both issues", issueViewIssueTitles(after))+ }+ })+ }+}++func TestListIssueViewIssuesHidesOtherMembersPrivateViews(t *testing.T) {+ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Private issue list",+ "scope_type": "workspace",+ "visibility": "private",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("create view: %d %s", code, body)+ }+ other := createSecondWorkspaceMember(t)+ listIssueViewIssuesForTest(t, other, view.ID, "").Want(http.StatusNotFound)+ listIssueViewIssuesForTest(t, testUserID, view.ID, "limit=1").Want(http.StatusOK)+}diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 25ca34ab82..0d67b8bcba 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -123,6 +123,24 @@ duplicate issue stops the operation before any position write. This protectsagainst truncated or repeated pages, but does not promise a snapshot acrossconcurrent edits. There is no CLI bulk-export or `--all` mode.+### Saved views++When a request names a saved view ("the Bugs view", a view link), read it+with `view issues` instead of rebuilding its filters from `issue list` flags:+the server applies every condition the view saves — "is not", the advanced+condition tree, relative due dates, project status — which `issue list`+cannot express.++```bash+multica view list --output json+multica view issues "Bugs" --output json --fields identifier,title,status+```++`<view>` is an ID, ID prefix, or exact name. Pages hold at most 100 issues;+while `has_more` is true, pass `next_cursor` to `--cursor`. Views and their+"me" conditions resolve against the runtime owner, so a member's private view+is only visible when that member owns the runtime.+## Custom properties: typed workflow stateWorkspaces may define custom issue properties (Severity, Environment, QA