Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9420: guest role scoped to shared projects (#10766)

Jiayuan Zhangec943222efba
diff --git a/apps/docs/content/docs/members-roles.fr.mdx b/apps/docs/content/docs/members-roles.fr.mdx
index 0f91a182dc..3fd34790a3 100644
--- a/apps/docs/content/docs/members-roles.fr.mdx
+++ b/apps/docs/content/docs/members-roles.fr.mdx
@@ -6,7 +6,7 @@ description: Invitez des membres et gérez les permissions de l'espace de travai
import { Callout } from "fumadocs-ui/components/callout";
import { RolesDemo } from "@/components/demos/roles-demo";
-Toute personne qui rejoint un [espace de travail](/workspaces) en est membre, et chaque membre a un rôle : `owner`, `admin` ou `member`. Les rôles ne contrôlent que les paramètres de l'espace de travail et la gestion de l'équipe ; la collaboration au quotidien — créer des tâches, écrire des commentaires — est ouverte à tous les membres.
+Toute personne qui rejoint un [espace de travail](/workspaces) en est membre, et chaque membre a un rôle : `owner`, `admin` ou `member`. Les rôles ne contrôlent que les paramètres de l'espace de travail et la gestion de l'équipe ; la collaboration au quotidien — créer des tâches, écrire des commentaires — est ouverte à tous les membres. Un espace de travail peut aussi avoir des [invités](#invités), qui ne voient que les projets partagés avec eux.
## Les trois rôles
@@ -33,7 +33,7 @@ Les rôles n'ouvrent pas non plus les projets privés. Un `owner` ou un `admin`
## Inviter des membres
-`owner` et `admin` cliquent sur **Inviter un membre** dans **Paramètres → Membres**, saisissent une adresse e-mail, choisissent un rôle et envoient l'invitation. Les invitations ne peuvent accorder que `admin` ou `member` ; un `owner` doit d'abord rejoindre l'espace de travail, puis être promu par un `owner` existant.
+`owner` et `admin` cliquent sur **Inviter un membre** dans **Paramètres → Membres**, saisissent une adresse e-mail, choisissent un rôle et envoient l'invitation. Les invitations peuvent accorder `admin`, `member` ou un accès [invité](#invités) ; un `owner` doit d'abord rejoindre l'espace de travail, puis être promu par un `owner` existant.
![Gestion des membres : le formulaire d'invitation et la liste des membres avec leurs rôles](/images/docs/members-roster.webp)
@@ -47,6 +47,14 @@ Pour obtenir un lien à transmettre directement, générez-en un dans l'onglet *
Sur Multica Cloud, un espace de travail au forfait Free peut compter jusqu'à 5 membres. Chaque membre et chaque invitation en attente occupe une place ; les invités n'en occupent pas. Tant que la limite s'applique, une nouvelle invitation, une invitation acceptée ou un accès par lien de partage qui la dépasserait est refusé, jusqu'à ce qu'une place se libère (invitation révoquée ou membre retiré) ou que l'espace de travail passe à un forfait supérieur. Les membres existants ne sont jamais retirés. Quand l'espace de travail est complet, les administrateurs voient **Mettre à niveau et inviter** dans la fenêtre d'invitation : une fois le paiement effectué, **Paramètres → Facturation** propose d'envoyer l'invitation mise de côté. Avec Pro et Business, chaque membre occupe un siège payant. Les espaces de travail auto-hébergés n'ont pas de limite de membres.
+## Invités
+
+Un invité ne voit que les projets partagés avec lui. Dans ces projets, il peut lire les tâches, les commenter, y réagir et les suivre ; il ne peut ni créer ni modifier de tâches, ni lancer ou mentionner d'agents, ni ouvrir les paramètres de l'espace de travail, et il ne voit aucun autre projet, agent, autopilot ou runtime. Les invités sont gratuits : ils n'occupent ni siège payant ni place de membre.
+
+`owner` et `admin` invitent un invité en choisissant **Invité** dans la fenêtre d'invitation et en sélectionnant les projets qu'il peut voir. Depuis le menu d'actions d'un membre, ils peuvent faire d'un membre un invité, ce qui libère son siège et lui retire ses agents, autopilots et accès aux runtimes ; faire d'un invité un membre, ce qui occupe un siège ; ou modifier les projets d'un invité avec **Gérer les projets accessibles**.
+
+Sur Multica Cloud, les invités sont inclus dans Pro et Business. À la fin d'un essai ou quand un espace de travail passe à Free, les invités existants gardent leur accès et peuvent toujours être retirés, restreints ou devenir membres, mais aucun nouvel invité ne peut être ajouté. Les espaces de travail auto-hébergés disposent des invités.
+
## Changer de rôle
Dans la liste des membres, ouvrez le menu d'actions à droite d'un membre et choisissez **Changer de rôle** ; le nouveau rôle s'applique immédiatement.
diff --git a/apps/docs/content/docs/members-roles.ja.mdx b/apps/docs/content/docs/members-roles.ja.mdx
index cef156e6a5..3da7cb792f 100644
--- a/apps/docs/content/docs/members-roles.ja.mdx
+++ b/apps/docs/content/docs/members-roles.ja.mdx
@@ -6,7 +6,7 @@ description: メンバーを招待し、owner、admin、member の 3 つのロ
import { Callout } from "fumadocs-ui/components/callout";
import { RolesDemo } from "@/components/demos/roles-demo";
-[ワークスペース](/workspaces)に参加した人は全員メンバーで、各メンバーは `owner`、`admin`、`member` のいずれか 1 つのロールを持ちます。ロールが制御するのはワークスペース設定とチーム管理だけです。タスクの作成やコメントの投稿といった日常のコラボレーションは、すべてのメンバーに開かれています。
+[ワークスペース](/workspaces)に参加した人は全員メンバーで、各メンバーは `owner`、`admin`、`member` のいずれか 1 つのロールを持ちます。ロールが制御するのはワークスペース設定とチーム管理だけです。タスクの作成やコメントの投稿といった日常のコラボレーションは、すべてのメンバーに開かれています。ワークスペースには[ゲスト](#ゲスト)を追加することもできます。ゲストには共有されたプロジェクトだけが表示されます。
## 3 つのロール
@@ -33,7 +33,7 @@ import { RolesDemo } from "@/components/demos/roles-demo";
## メンバーの招待
-`owner` と `admin` は**設定 → メンバー**で**メンバーを招待**をクリックし、メールアドレスを入力してロールを選び、送信します。招待で付与できるのは `admin` または `member` だけです。`owner` にするには、先にワークスペースへ参加してもらい、既存の `owner` が昇格させます。
+`owner` と `admin` は**設定 → メンバー**で**メンバーを招待**をクリックし、メールアドレスを入力してロールを選び、送信します。招待で付与できるのは `admin`、`member`、または[ゲスト](#ゲスト)です。`owner` にするには、先にワークスペースへ参加してもらい、既存の `owner` が昇格させます。
![メンバー管理:招待フォームとロール付きのメンバー一覧](/images/docs/members-roster.webp)
@@ -47,6 +47,14 @@ import { RolesDemo } from "@/components/demos/roles-demo";
Multica Cloud では、Free プランのワークスペースのメンバーは最大 5 人です。メンバーと保留中の招待がそれぞれ 1 枠を使い、ゲストは枠を使いません。上限が適用されている間は、上限を超える新しい招待、招待の承諾、共有リンクからの参加は拒否されます。枠が空く(招待を取り消す、メンバーを削除する)か、ワークスペースをアップグレードすると再び追加できます。既存のメンバーが削除されることはありません。ワークスペースが満員のとき、管理者には招待ダイアログに**アップグレードして招待**が表示されます。支払いが完了すると、**設定 → 請求とプラン**で保留中の招待を送信できます。Pro と Business では、メンバーごとに有料席が必要です。セルフホストのワークスペースにはメンバー数の上限はありません。
+## ゲスト
+
+ゲストには、共有されたプロジェクトだけが表示されます。それらのプロジェクトでは、タスクの閲覧、コメント、リアクション、フォローができます。タスクの作成や編集、エージェントの実行やメンション、ワークスペース設定の表示はできず、ほかのプロジェクト、エージェント、オートパイロット、ランタイムも見えません。ゲストは無料で、有料席もメンバー枠も使いません。
+
+`owner` と `admin` は、招待ダイアログで**ゲスト**を選び、表示するプロジェクトを指定してゲストを招待します。メンバーのアクションメニューからは、メンバーをゲストにする(席が空き、エージェント、オートパイロット、ランタイムへのアクセスが取り消されます)、ゲストをメンバーにする(席を 1 つ使います)、**アクセスできるプロジェクトを管理**でゲストのプロジェクトを変更する、といった操作ができます。
+
+Multica Cloud では、ゲストは Pro と Business に含まれます。トライアルが終了したりワークスペースが Free に移行したりしても、既存のゲストはアクセスを保持し、削除、範囲の縮小、メンバーへの変更は引き続き行えますが、新しいゲストは追加できません。セルフホストのワークスペースではゲストを利用できます。
+
## ロールの変更
メンバー一覧で対象メンバーの右側にある操作メニューを開き、**ロールを変更**を選びます。変更はただちに反映されます。
diff --git a/apps/docs/content/docs/members-roles.ko.mdx b/apps/docs/content/docs/members-roles.ko.mdx
index 536ef1eb9e..8267be43a6 100644
--- a/apps/docs/content/docs/members-roles.ko.mdx
+++ b/apps/docs/content/docs/members-roles.ko.mdx
@@ -6,7 +6,7 @@ description: 멤버를 초대하고 owner, admin, member 세 가지 역할로
import { Callout } from "fumadocs-ui/components/callout";
import { RolesDemo } from "@/components/demos/roles-demo";
-[워크스페이스](/workspaces)에 참여한 사람은 모두 멤버이며, 각 멤버는 `owner`, `admin`, `member` 중 하나의 역할을 가집니다. 역할은 워크스페이스 설정과 팀 관리 권한만 제어합니다. 태스크 생성, 댓글 작성 같은 일상적인 협업은 모든 멤버에게 열려 있습니다.
+[워크스페이스](/workspaces)에 참여한 사람은 모두 멤버이며, 각 멤버는 `owner`, `admin`, `member` 중 하나의 역할을 가집니다. 역할은 워크스페이스 설정과 팀 관리 권한만 제어합니다. 태스크 생성, 댓글 작성 같은 일상적인 협업은 모든 멤버에게 열려 있습니다. 워크스페이스에는 [게스트](#게스트)도 둘 수 있으며, 게스트는 공유받은 프로젝트만 볼 수 있습니다.
## 세 가지 역할
@@ -33,7 +33,7 @@ import { RolesDemo } from "@/components/demos/roles-demo";
## 멤버 초대
-`owner`와 `admin`은 **설정 → 멤버**에서 **멤버 초대**를 누르고 이메일을 입력한 뒤 역할을 선택해 초대를 보냅니다. 초대 시 부여할 수 있는 역할은 `admin`과 `member`뿐입니다. `owner`로 지정하려면 먼저 워크스페이스에 참여한 다음 기존 `owner`가 역할을 올려야 합니다.
+`owner`와 `admin`은 **설정 → 멤버**에서 **멤버 초대**를 누르고 이메일을 입력한 뒤 역할을 선택해 초대를 보냅니다. 초대 시 `admin`, `member` 또는 [게스트](#게스트)로 초대할 수 있습니다. `owner`로 지정하려면 먼저 워크스페이스에 참여한 다음 기존 `owner`가 역할을 올려야 합니다.
![멤버 관리: 초대 양식과 역할이 표시된 멤버 명단](/images/docs/members-roster.webp)
@@ -47,6 +47,14 @@ import { RolesDemo } from "@/components/demos/roles-demo";
Multica Cloud에서 Free 요금제 워크스페이스는 멤버를 최대 5명까지 둘 수 있습니다. 멤버와 대기 중인 초대가 각각 한 자리를 차지하며, 게스트는 자리를 차지하지 않습니다. 한도가 적용되는 동안에는 한도를 넘는 새 초대, 초대 수락, 공유 링크를 통한 참여가 거부됩니다. 자리가 생기거나(초대 취소 또는 멤버 제거) 워크스페이스를 업그레이드하면 다시 추가할 수 있습니다. 기존 멤버는 제거되지 않습니다. 워크스페이스가 가득 차면 관리자는 초대 대화 상자에서 **업그레이드하고 초대**를 볼 수 있습니다. 결제가 완료되면 **설정 → 결제 및 요금제**에서 보류해 둔 초대를 보낼 수 있습니다. Pro와 Business에서는 멤버마다 유료 좌석이 필요합니다. 셀프 호스팅 워크스페이스에는 멤버 수 한도가 없습니다.
+## 게스트
+
+게스트는 공유받은 프로젝트만 볼 수 있습니다. 그 프로젝트에서는 태스크를 보고, 댓글을 달고, 반응을 남기고, 팔로우할 수 있습니다. 태스크를 만들거나 수정할 수 없고, 에이전트를 실행하거나 멘션할 수 없으며, 워크스페이스 설정도 열 수 없습니다. 다른 프로젝트, 에이전트, 오토파일럿, 런타임도 보이지 않습니다. 게스트는 무료이며 유료 좌석이나 멤버 자리를 차지하지 않습니다.
+
+`owner`와 `admin`은 초대 대화 상자에서 **게스트**를 선택하고 볼 수 있는 프로젝트를 골라 게스트를 초대합니다. 멤버의 작업 메뉴에서는 멤버를 게스트로 바꾸거나(좌석이 비고 에이전트, 오토파일럿, 런타임 접근 권한이 회수됩니다), 게스트를 멤버로 바꾸거나(좌석을 하나 사용합니다), **접근 가능한 프로젝트 관리**로 게스트의 프로젝트를 바꿀 수 있습니다.
+
+Multica Cloud에서 게스트는 Pro와 Business에 포함됩니다. 체험이 끝나거나 워크스페이스가 Free로 바뀌어도 기존 게스트는 접근 권한을 유지하며 제거, 범위 축소, 멤버 전환은 계속할 수 있지만 새 게스트는 추가할 수 없습니다. 셀프 호스팅 워크스페이스에서는 게스트를 사용할 수 있습니다.
+
## 역할 변경
멤버 목록에서 해당 멤버 오른쪽의 작업 메뉴를 열고 **역할 변경**을 선택하면 즉시 적용됩니다.
diff --git a/apps/docs/content/docs/members-roles.mdx b/apps/docs/content/docs/members-roles.mdx
index fd291645ff..1bff6b979c 100644
--- a/apps/docs/content/docs/members-roles.mdx
+++ b/apps/docs/content/docs/members-roles.mdx
@@ -6,7 +6,7 @@ description: Invite members and manage workspace permissions with the owner, adm
import { Callout } from "fumadocs-ui/components/callout";
import { RolesDemo } from "@/components/demos/roles-demo";
-Everyone who joins a [workspace](/workspaces) is a member, and each member has one role: `owner`, `admin`, or `member`. Roles only control workspace settings and team management; day-to-day collaboration — creating issues, writing comments — is open to all members.
+Everyone who joins a [workspace](/workspaces) is a member, and each member has one role: `owner`, `admin`, or `member`. Roles only control workspace settings and team management; day-to-day collaboration — creating issues, writing comments — is open to all members. A workspace can also have [guests](#guests), who see only the projects shared with them.
## The three roles
@@ -33,7 +33,7 @@ Roles do not open private projects either. An `owner` or `admin` sees a private
## Invite members
-`owner` and `admin` open **Settings → Members**, click **Invite member**, enter an email, pick a role, and send. Invitations can only grant `admin` or `member`; an `owner` must join the workspace first and then be promoted by an existing `owner`.
+`owner` and `admin` open **Settings → Members**, click **Invite member**, enter an email, pick a role, and send. Invitations can grant `admin`, `member`, or [guest](#guests) access; an `owner` must join the workspace first and then be promoted by an existing `owner`.
![Member management: the invite form and the roster with roles](/images/docs/members-roster.webp)
@@ -47,6 +47,14 @@ When you need a link you can pass along yourself, generate one under **Share lin
On Multica Cloud, a workspace on the Free plan can have up to 5 members. Members and pending invitations each take a slot; guests take none. While the limit applies, a new invitation, an accepted invitation or a share-link join that would go past it is refused until a slot frees up (an invitation is revoked or a member removed) or the workspace upgrades. Existing members are never removed. When the workspace is full, admins see **Upgrade and invite** in the invite dialog: once the payment goes through, **Settings → Billing** offers to send the held invitation. On Pro and Business each member takes a paid seat. Self-hosted workspaces have no member limit.
+## Guests
+
+A guest sees only the projects shared with it. In those projects it can read issues, comment, react, and follow them; it cannot create or edit issues, run or mention agents, or open workspace settings, and it sees no other projects, agents, autopilots, or runtimes. Guests are free: they take no paid seat and no member slot.
+
+`owner` and `admin` invite a guest by choosing **Guest** in the invite dialog and picking the projects it can see. From a member's actions menu they can make a member a guest, which frees its seat and takes back its agents, autopilots, and runtime access; make a guest a member, which takes a seat; or change a guest's projects with **Manage accessible projects**.
+
+On Multica Cloud, guests are included in Pro and Business. When a trial ends or a workspace moves to Free, existing guests keep their access and can still be removed, narrowed, or made members, but no new guests can be added. Self-hosted workspaces have guests.
+
## Change roles
In the member list, open the actions menu at the right of a member's row and choose **Change role**. The new role takes effect immediately.
diff --git a/apps/docs/content/docs/members-roles.zh-Hant.mdx b/apps/docs/content/docs/members-roles.zh-Hant.mdx
index 3bcddfb244..1f3045eef6 100644
--- a/apps/docs/content/docs/members-roles.zh-Hant.mdx
+++ b/apps/docs/content/docs/members-roles.zh-Hant.mdx
@@ -6,7 +6,7 @@ description: 邀請成員,並用 owner、admin 和 member 三種角色管理
import { Callout } from "fumadocs-ui/components/callout";
import { RolesDemo } from "@/components/demos/roles-demo";
-加入[工作區](/workspaces)的人都是成員,每位成員有一個角色:`owner`、`admin` 或 `member`。角色只控制工作區設定和團隊管理;建立任務、發表評論等日常協作對所有成員開放。
+加入[工作區](/workspaces)的人都是成員,每位成員有一個角色:`owner`、`admin` 或 `member`。角色只控制工作區設定和團隊管理;建立任務、發表評論等日常協作對所有成員開放。工作區還可以有[訪客](#訪客),訪客只能看到分享給自己的專案。
## 三種角色
@@ -33,7 +33,7 @@ import { RolesDemo } from "@/components/demos/roles-demo";
## 邀請成員
-`owner` 和 `admin` 在**設定 → 成員**中點選**邀請成員**,填寫信箱、選擇角色後傳送。邀請只能授予 `admin` 或 `member`;`owner` 需要先加入工作區,再由現有 `owner` 提升。
+`owner` 和 `admin` 在**設定 → 成員**中點選**邀請成員**,填寫信箱、選擇角色後傳送。邀請可以授予 `admin`、`member` 或[訪客](#訪客)身分;`owner` 需要先加入工作區,再由現有 `owner` 提升。
![成員管理:邀請表單與帶角色的成員名冊](/images/docs/members-roster.webp)
@@ -47,6 +47,14 @@ import { RolesDemo } from "@/components/demos/roles-demo";
在 Multica Cloud 上,Free 套餐的工作區最多 5 位成員。成員和待接受的邀請各佔一個名額,訪客不佔。上限生效時,超出上限的新邀請、接受邀請和透過分享連結加入都會被拒絕,直到空出名額(撤回邀請或移除成員)或工作區升級。既有成員不會被移除。工作區滿員時,管理員會在邀請視窗裡看到**升級並邀請**:付款完成後,在**設定 → 帳單與套餐**裡可以發出這份邀請。Pro 和 Business 每位成員佔一個付費席位。自行部署的工作區沒有成員上限。
+## 訪客
+
+訪客只能看到分享給自己的專案。在這些專案裡,訪客可以查看任務、評論、加上表情回應和關注任務;不能建立或修改任務,不能執行或 @ agent,也不能開啟工作區設定,看不到其他專案、agent、autopilot 和 runtime。訪客免費,不佔付費席位,也不佔成員名額。
+
+`owner` 和 `admin` 在邀請視窗裡選擇**訪客**並勾選可存取的專案,即可邀請訪客。在成員的操作選單裡,可以把成員設為訪客(釋出其席位,並收回其 agent、autopilot 和 runtime 權限),把訪客設為成員(佔用一個席位),或透過**管理可存取的專案**調整訪客能看到的專案。
+
+在 Multica Cloud 上,Pro 和 Business 包含訪客。試用結束或工作區降到 Free 後,既有訪客保留存取權限,仍然可以移除、縮小範圍或設為成員,但不能再新增訪客。自行部署的工作區可以使用訪客。
+
## 調整角色
在成員列表中開啟某位成員右側的操作選單,選擇**更改角色**,角色立即生效。
diff --git a/apps/docs/content/docs/members-roles.zh.mdx b/apps/docs/content/docs/members-roles.zh.mdx
index ddeffb013c..69cb11db83 100644
--- a/apps/docs/content/docs/members-roles.zh.mdx
+++ b/apps/docs/content/docs/members-roles.zh.mdx
@@ -6,7 +6,7 @@ description: 邀请成员,并用 owner、admin 和 member 三种角色管理
import { Callout } from "fumadocs-ui/components/callout";
import { RolesDemo } from "@/components/demos/roles-demo";
-加入[工作区](/workspaces)的人都是成员,每位成员有一个角色:`owner`、`admin` 或 `member`。角色只控制工作区设置和团队管理;创建任务、发表评论等日常协作对所有成员开放。
+加入[工作区](/workspaces)的人都是成员,每位成员有一个角色:`owner`、`admin` 或 `member`。角色只控制工作区设置和团队管理;创建任务、发表评论等日常协作对所有成员开放。工作区还可以有[访客](#访客),访客只能看到分享给自己的项目。
## 三种角色
@@ -33,7 +33,7 @@ import { RolesDemo } from "@/components/demos/roles-demo";
## 邀请成员
-`owner` 和 `admin` 在**设置 → 成员**中点击**邀请成员**,填写邮箱、选择角色后发送。邀请只能授予 `admin` 或 `member`;`owner` 需要先加入工作区,再由现有 `owner` 提升。
+`owner` 和 `admin` 在**设置 → 成员**中点击**邀请成员**,填写邮箱、选择角色后发送。邀请可以授予 `admin`、`member` 或[访客](#访客)身份;`owner` 需要先加入工作区,再由现有 `owner` 提升。
![成员管理:邀请表单与带角色的成员名册](/images/docs/members-roster.webp)
@@ -47,6 +47,14 @@ import { RolesDemo } from "@/components/demos/roles-demo";
在 Multica Cloud 上,Free 套餐的工作区最多 5 位成员。成员和待接受的邀请各占一个名额,访客不占。上限生效时,超出上限的新邀请、接受邀请和通过分享链接加入都会被拒绝,直到空出名额(撤回邀请或移除成员)或工作区升级。已有成员不会被移除。工作区满员时,管理员会在邀请弹窗里看到**升级并邀请**:付款完成后,在**设置 → 账单与套餐**里可以发出这份邀请。Pro 和 Business 每位成员占一个付费席位。自部署的工作区没有成员上限。
+## 访客
+
+访客只能看到分享给自己的项目。在这些项目里,访客可以查看任务、评论、添加表情回应和关注任务;不能创建或修改任务,不能运行或 @ agent,也不能打开工作区设置,看不到其他项目、agent、autopilot 和 runtime。访客免费,不占付费席位,也不占成员名额。
+
+`owner` 和 `admin` 在邀请弹窗里选择**访客**并勾选可访问的项目,即可邀请访客。在成员的操作菜单里,可以把成员设为访客(释放其席位,并收回其 agent、autopilot 和 runtime 权限),把访客设为成员(占用一个席位),或通过**管理可访问的项目**调整访客能看到的项目。
+
+在 Multica Cloud 上,Pro 和 Business 包含访客。试用结束或工作区降到 Free 后,已有访客保留访问权限,仍然可以移除、缩小范围或设为成员,但不能再添加新访客。自部署的工作区可以使用访客。
+
## 调整角色
在成员列表中打开某位成员右侧的操作菜单,选择**更改角色**,角色立即生效。
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx b/apps/mobile/app/(app)/[workspace]/issue/[id].tsx
index 01217a7bb1..4dce3f9872 100644
--- a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx
+++ b/apps/mobile/app/(app)/[workspace]/issue/[id].tsx
@@ -44,6 +44,7 @@ import { useViewedIssuesStore } from "@/data/viewed-issues-store";
import { useCommentSelectStore } from "@/data/comment-select-store";
import { useReplyTargetStore } from "@/data/stores/reply-target-store";
import { useT } from "@/lib/i18n";
+import { useIsGuest } from "@/lib/use-is-guest";
export default function IssueDetail() {
// `highlight` + `h` come from inbox deep-link (apps/mobile/app/(app)/
@@ -107,6 +108,8 @@ export default function IssueDetail() {
const createPin = useCreatePin();
const deletePin = useDeletePin();
const { t } = useT("issues");
+ // A guest (MUL-9420) reads and comments: no editing, deleting, or agent runs.
+ const guest = useIsGuest();
// Three-dot menu: Pin/Unpin / Copy link / Open on web (if web URL set) /
// Delete. Mirrors apps/mobile/app/(app)/[workspace]/project/[id].tsx — same
@@ -121,10 +124,10 @@ export default function IssueDetail() {
: null;
const actions = ["cancel", "pin"];
if (isPinned) actions[1] = "unpin";
- actions.push("edit");
+ if (!guest) actions.push("edit");
if (issueLink) actions.push("copy_link");
if (issueLink) actions.push("open_web");
- actions.push("delete");
+ if (!guest) actions.push("delete");
const options = actions.map((action) =>
action === "cancel"
? t("common:actions.cancel")
@@ -140,12 +143,12 @@ export default function IssueDetail() {
? t("menu.open_web")
: t("menu.delete_issue"),
);
- const destructiveIndex = options.length - 1;
+ const destructiveIndex = actions.indexOf("delete");
ActionSheetIOS.showActionSheetWithOptions(
{
options,
cancelButtonIndex: 0,
- destructiveButtonIndex: destructiveIndex,
+ ...(destructiveIndex >= 0 ? { destructiveButtonIndex: destructiveIndex } : {}),
title: issue.identifier,
},
(i) => {
@@ -175,7 +178,7 @@ export default function IssueDetail() {
}
},
);
- }, [issue, wsSlug, deleteIssue, isPinned, createPin, deletePin, t]);
+ }, [issue, wsSlug, deleteIssue, isPinned, createPin, deletePin, guest, t]);
return (
<View className="flex-1 bg-background">
@@ -189,7 +192,7 @@ export default function IssueDetail() {
{/* Ambient agent-working badge — renders null when no
* active tasks, so it doesn't crowd the header in the
* common case. See agent-header-badge.tsx. */}
- <AgentHeaderBadge issueId={id} />
+ {!guest && <AgentHeaderBadge issueId={id} />}
<IconButton
name="ellipsis-horizontal"
onPress={onPressMore}
diff --git a/apps/mobile/components/issue/attribute-row.tsx b/apps/mobile/components/issue/attribute-row.tsx
index 62c0f4e948..7819cbe1b9 100644
--- a/apps/mobile/components/issue/attribute-row.tsx
+++ b/apps/mobile/components/issue/attribute-row.tsx
@@ -14,6 +14,9 @@
* labels → issue/[id]/picker/label (multi-select, stays open)
* project → issue/[id]/picker/project
* due_date → issue/[id]/picker/due-date
+ *
+ * `readOnly` (a guest, MUL-9420) renders the same chips without pickers and
+ * drops the empty label / due-date placeholders, which only invite an edit.
*/
import { useMemo } from "react";
import { View } from "react-native";
@@ -80,7 +83,13 @@ function formatDueDate(iso: string | null): string | null {
);
}
-export function AttributeRow({ issue }: { issue: Issue }) {
+export function AttributeRow({
+ issue,
+ readOnly = false,
+}: {
+ issue: Issue;
+ readOnly?: boolean;
+}) {
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
const wsSlug = useWorkspaceStore((s) => s.currentWorkspaceSlug);
const { getName } = useActorLookup();
@@ -110,13 +119,17 @@ export function AttributeRow({ issue }: { issue: Issue }) {
: null;
const dueLabel = formatDueDate(issue.due_date);
- const openPicker = (field: IssuePickerField) => {
- if (!wsSlug) return;
- router.push({
- pathname: ISSUE_PICKER_PATHNAMES[field],
- params: { workspace: wsSlug, id: issue.id },
- });
- };
+ // Undefined for a read-only row: AttributeChip then renders a plain View.
+ const pickerFor = (field: IssuePickerField) =>
+ readOnly
+ ? undefined
+ : () => {
+ if (!wsSlug) return;
+ router.push({
+ pathname: ISSUE_PICKER_PATHNAMES[field],
+ params: { workspace: wsSlug, id: issue.id },
+ });
+ };
return (
<View className="flex-row flex-wrap gap-2">
@@ -132,7 +145,7 @@ export function AttributeRow({ issue }: { issue: Issue }) {
}
label={labelOf(issue.status)}
variant="filled"
- onPress={() => openPicker("status")}
+ onPress={pickerFor("status")}
/>
{/* Priority */}
@@ -140,7 +153,7 @@ export function AttributeRow({ issue }: { issue: Issue }) {
icon={<PriorityIcon priority={issue.priority} size={14} />}
label={t(PRIORITY_CHIP_LABEL[issue.priority])}
variant={issue.priority === "none" ? "dimmed" : "filled"}
- onPress={() => openPicker("priority")}
+ onPress={pickerFor("priority")}
/>
{/* Assignee */}
@@ -156,7 +169,7 @@ export function AttributeRow({ issue }: { issue: Issue }) {
}
label={assigneeName ?? t("picker.unknown")}
variant="filled"
- onPress={() => openPicker("assignee")}
+ onPress={pickerFor("assignee")}
/>
) : (
<AttributeChip
@@ -165,7 +178,7 @@ export function AttributeRow({ issue }: { issue: Issue }) {
}
label={t("filters.assignee")}
variant="dimmed"
- onPress={() => openPicker("assignee")}
+ onPress={pickerFor("assignee")}
/>
)}
@@ -184,15 +197,15 @@ export function AttributeRow({ issue }: { issue: Issue }) {
}
label={label.name}
variant="filled"
- onPress={() => openPicker("label")}
+ onPress={pickerFor("label")}
/>
))}
- {labels.length === 0 ? (
+ {labels.length === 0 && !readOnly ? (
<AttributeChip
icon={<Text className="text-xs text-muted-foreground/70">◯</Text>}
label={t("filters.label")}
variant="dimmed"
- onPress={() => openPicker("label")}
+ onPress={pickerFor("label")}
/>
) : null}
@@ -202,7 +215,7 @@ export function AttributeRow({ issue }: { issue: Issue }) {
icon={<ProjectIcon icon={project.icon} size="sm" />}
label={project.title}
variant="filled"
- onPress={() => openPicker("project")}
+ onPress={pickerFor("project")}
/>
) : (
<AttributeChip
@@ -211,17 +224,19 @@ export function AttributeRow({ issue }: { issue: Issue }) {
}
label={t("filters.project")}
variant="dimmed"
- onPress={() => openPicker("project")}
+ onPress={pickerFor("project")}
/>
)}
{/* Due date */}
- <AttributeChip
- icon={<Text className="text-xs text-muted-foreground/80">📅</Text>}
- label={dueLabel ?? t("common:fields.due_date")}
- variant={dueLabel ? "filled" : "dimmed"}
- onPress={() => openPicker("due-date")}
- />
+ {dueLabel || !readOnly ? (
+ <AttributeChip
+ icon={<Text className="text-xs text-muted-foreground/80">📅</Text>}
+ label={dueLabel ?? t("common:fields.due_date")}
+ variant={dueLabel ? "filled" : "dimmed"}
+ onPress={pickerFor("due-date")}
+ />
+ ) : null}
</View>
);
}
diff --git a/apps/mobile/components/issue/issue-header-card.tsx b/apps/mobile/components/issue/issue-header-card.tsx
index 78173bd6e3..2ca96f797a 100644
--- a/apps/mobile/components/issue/issue-header-card.tsx
+++ b/apps/mobile/components/issue/issue-header-card.tsx
@@ -5,7 +5,8 @@
* - identifier (MUL-NN) above as a small muted label
* - title in a large bold treatment
* - attribute chip row below (status / priority / assignee / labels /
- * project / due date) — tappable, opens picker sheets
+ * project / due date) — tappable, opens picker sheets; read-only for a
+ * guest (MUL-9420), who also sees no agent activity
*
* The native iOS Stack header still renders `issue.identifier` as the
* navigation title; the body re-renders it more prominently per the
@@ -16,8 +17,10 @@ import type { Issue } from "@multica/core/types";
import { Text } from "@/components/ui/text";
import { AttributeRow } from "./attribute-row";
import { AgentActivityRow } from "./agent-activity-row";
+import { useIsGuest } from "@/lib/use-is-guest";
export function IssueHeaderCard({ issue }: { issue: Issue }) {
+ const guest = useIsGuest();
return (
<View className="px-4 pt-4 pb-3 gap-3">
<Text className="text-xs text-muted-foreground">{issue.identifier}</Text>
@@ -28,8 +31,8 @@ export function IssueHeaderCard({ issue }: { issue: Issue }) {
* "who's doing this issue right now / who has done it" (dynamic),
* which is higher-IA than the static property chips below.
* Conditionally renders null when there are no tasks at all. */}
- <AgentActivityRow issueId={issue.id} />
- <AttributeRow issue={issue} />
+ {!guest && <AgentActivityRow issueId={issue.id} />}
+ <AttributeRow issue={issue} readOnly={guest} />
</View>
);
}
diff --git a/apps/mobile/components/issue/mention-suggestion-bar.tsx b/apps/mobile/components/issue/mention-suggestion-bar.tsx
index ee7062aad9..15e2d83072 100644
--- a/apps/mobile/components/issue/mention-suggestion-bar.tsx
+++ b/apps/mobile/components/issue/mention-suggestion-bar.tsx
@@ -51,6 +51,7 @@ import {
import type { MentionMarker } from "@/lib/mention-serialize";
import { cn } from "@/lib/utils";
import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
+import { isGuestRole } from "@/lib/member-role";
type Mode = "comment" | "chat";
@@ -161,7 +162,11 @@ export function MentionSuggestionBar({
}
// Comment mode.
- const showAll = !q || "all".startsWith(q);
+ const myRole =
+ members.find((m) => m.user_id === userId)?.role ?? null;
+ // A guest (MUL-9420) mentions people only — see comment-mention-candidates.
+ const guest = isGuestRole(myRole);
+ const showAll = !guest && (!q || "all".startsWith(q));
const matchedMembers = [...members]
.filter((m) => !q || m.name.toLowerCase().includes(q))
.sort((a, b) => a.name.localeCompare(b.name));
@@ -169,8 +174,6 @@ export function MentionSuggestionBar({
// mirrors web (packages/views/editor/extensions/mention-suggestion.tsx:418-424).
// A private agent shown in the suggestion list would create a mention the
// assignee can never act on; web hides them, mobile must too.
- const myRole =
- members.find((m) => m.user_id === userId)?.role ?? null;
const runnableAgentIds = new Set(
agents
.filter(
@@ -182,6 +185,7 @@ export function MentionSuggestionBar({
const matchedAgents = [...agents]
.filter(
(a) =>
+ !guest &&
!a.archived_at &&
isAgentRuntimeBound(a) &&
(!q || a.name.toLowerCase().includes(q)) &&
@@ -193,6 +197,7 @@ export function MentionSuggestionBar({
const matchedSquads = [...squads]
.filter(
(s) =>
+ !guest &&
!s.archived_at &&
runnableAgentIds.has(s.leader_id) &&
(!q || s.name.toLowerCase().includes(q)),
diff --git a/apps/mobile/components/issue/pickers/mention-picker-body.tsx b/apps/mobile/components/issue/pickers/mention-picker-body.tsx
index 3c87693fd6..8922a6d20c 100644
--- a/apps/mobile/components/issue/pickers/mention-picker-body.tsx
+++ b/apps/mobile/components/issue/pickers/mention-picker-body.tsx
@@ -48,6 +48,8 @@ import {
import { useScrollToTopOnChange } from "@/lib/use-scroll-to-top-on-change";
import { THEME } from "@/lib/theme";
import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
+import { commentMentionCandidates } from "@/lib/comment-mention-candidates";
+import { useIsGuest } from "@/lib/use-is-guest";
import { cn } from "@/lib/utils";
import { useT } from "@/lib/i18n";
@@ -76,9 +78,18 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
const { t } = useT("issues");
// Rows are icon-only here too — colour is what names a custom status.
const catalog = useIssueStatuses();
+ // A guest (MUL-9420) mentions people only, so it skips the agent and squad
+ // lists the server would refuse it anyway.
+ const guest = useIsGuest();
const { data: members = [] } = useQuery(memberListOptions(wsId));
- const { data: agents = [] } = useQuery(agentListOptions(wsId));
- const { data: squads = [] } = useQuery(squadListOptions(wsId));
+ const { data: agents = [] } = useQuery({
+ ...agentListOptions(wsId),
+ enabled: !!wsId && !guest,
+ });
+ const { data: squads = [] } = useQuery({
+ ...squadListOptions(wsId),
+ enabled: !!wsId && !guest,
+ });
const runnableAgentIds = useMemo(
() =>
new Set(
@@ -144,9 +155,6 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
};
const rows = useMemo<Row[]>(() => {
- const q = query.trim().toLowerCase();
- const matchName = (name: string) => !q || name.toLowerCase().includes(q);
-
const out: Row[] = [];
// People-style sections only render in comment mode. Chat is single-
@@ -154,29 +162,33 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
// people. The Issues section IS useful in chat ("reference ticket
// for context"), so it stays for both modes.
if (mode === "comment") {
- if (!q || "all".includes(q)) {
+ const candidates = commentMentionCandidates({
+ query,
+ members,
+ agents,
+ squads,
+ guest,
+ });
+ if (candidates.all) {
out.push({ kind: "all" });
}
- const memberRows = [...members]
- .filter((m) => matchName(m.name))
- .sort((a, b) => a.name.localeCompare(b.name))
- .map((m): Row => ({ kind: "member", member: m }));
- if (memberRows.length > 0) {
- out.push({ kind: "section", label: t("picker.people") }, ...memberRows);
+ if (candidates.members.length > 0) {
+ out.push(
+ { kind: "section", label: t("picker.people") },
+ ...candidates.members.map((m): Row => ({ kind: "member", member: m })),
+ );
}
- const agentRows = [...agents]
- .filter((a) => matchName(a.name))
- .sort((a, b) => a.name.localeCompare(b.name))
- .map((a): Row => ({ kind: "agent", agent: a }));
- if (agentRows.length > 0) {
- out.push({ kind: "section", label: t("picker.agents") }, ...agentRows);
+ if (candidates.agents.length > 0) {
+ out.push(
+ { kind: "section", label: t("picker.agents") },
+ ...candidates.agents.map((a): Row => ({ kind: "agent", agent: a })),
+ );
}
- const squadRows = [...squads]
- .filter((s) => !s.archived_at && matchName(s.name))
- .sort((a, b) => a.name.localeCompare(b.name))
- .map((s): Row => ({ kind: "squad", squad: s }));
- if (squadRows.length > 0) {
- out.push({ kind: "section", label: t("picker.squads") }, ...squadRows);
+ if (candidates.squads.length > 0) {
+ out.push(
+ { kind: "section", label: t("picker.squads") },
+ ...candidates.squads.map((s): Row => ({ kind: "squad", squad: s })),
+ );
}
}
@@ -187,7 +199,7 @@ export function MentionPickerBody({ query, mode = "comment" }: Props) {
}
}
return out;
- }, [mode, members, agents, squads, issueResults, query, t]);
+ }, [mode, members, agents, squads, guest, issueResults, query, t]);
const pick = (row: Row) => {
let chip: MentionChipDraft | null = null;
diff --git a/apps/mobile/components/ui/app-header-actions.tsx b/apps/mobile/components/ui/app-header-actions.tsx
index 06b42cceab..f57cf48f87 100644
--- a/apps/mobile/components/ui/app-header-actions.tsx
+++ b/apps/mobile/components/ui/app-header-actions.tsx
@@ -1,6 +1,7 @@
/**
* Header utility buttons shared across primary tabs (Inbox / My Issues).
- * Provides two global actions on the right: search and create-issue.
+ * Provides two global actions on the right: search and create-issue. A
+ * guest (MUL-9420) cannot create issues, so it gets search only.
*
* The workspace menu (global nav, workspace switcher, settings) is reached
* via the "More" tab in the bottom bar.
@@ -12,10 +13,12 @@ import { router } from "expo-router";
import { IconButton } from "@/components/ui/icon-button";
import { useWorkspaceStore } from "@/data/workspace-store";
import { useT } from "@/lib/i18n";
+import { useIsGuest } from "@/lib/use-is-guest";
export function HeaderActions() {
const slug = useWorkspaceStore((s) => s.currentWorkspaceSlug);
const { t } = useT();
+ const guest = useIsGuest();
const onSearch = () => {
if (slug) router.push(`/${slug}/search`);
@@ -31,12 +34,14 @@ export function HeaderActions() {
onPress={onSearch}
accessibilityLabel={t("common:actions.search")}
/>
- <IconButton
- name="add"
- iconSize={24}
- onPress={onCreate}
- accessibilityLabel={t("navigation:routes.new_issue")}
- />
+ {!guest && (
+ <IconButton
+ name="add"
+ iconSize={24}
+ onPress={onCreate}
+ accessibilityLabel={t("navigation:routes.new_issue")}
+ />
+ )}
</>
);
}
diff --git a/apps/mobile/data/schemas.test.ts b/apps/mobile/data/schemas.test.ts
index 6a5d562642..79be73afd4 100644
--- a/apps/mobile/data/schemas.test.ts
+++ b/apps/mobile/data/schemas.test.ts
@@ -2,6 +2,8 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { parseWithFallback } from "@/lib/parse-response";
import {
+ MemberListSchema,
+ MemberWithUserSchema,
ProjectSchema,
EMPTY_TASK_MESSAGE_LIST,
TaskMessageListSchema,
@@ -64,3 +66,20 @@ describe("TaskMessageListSchema", () => {
).toEqual([]);
});
});
+
+describe("MemberWithUserSchema role", () => {
+ const member = {
+ id: "m-1", workspace_id: "ws-1", user_id: "u-1", created_at: "2026-01-01T00:00:00Z",
+ name: "Guest", email: "[email protected]", avatar_url: null,
+ };
+ it.each(["owner", "admin", "member", "guest"] as const)("keeps the %s role", (role) => {
+ expect(MemberWithUserSchema.parse({ ...member, role }).role).toBe(role);
+ });
+ it("does not fold a guest into a member (MUL-9420)", () => {
+ const [parsed] = MemberListSchema.parse([{ ...member, role: "guest", project_ids: ["p-1"] }]);
+ expect(parsed).toMatchObject({ role: "guest", project_ids: ["p-1"] });
+ });
+ it("still falls back to member for an unknown role", () => {
+ expect(MemberWithUserSchema.parse({ ...member, role: "superuser" }).role).toBe("member");
+ });
+});
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 87a892f754..19e10e92bd 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -620,7 +620,9 @@ export const MemberWithUserSchema: z.ZodType<MemberWithUser> = z.object({
id: z.string(),
workspace_id: z.string().default(""),
user_id: z.string().default(""),
- role: z.enum(["owner", "admin", "member"]).catch("member"),
+ // `guest` (MUL-9420) must survive parsing: folded into `member`, a guest
+ // would be offered every member control the server then refuses.
+ role: z.enum(["owner", "admin", "member", "guest"]).catch("member"),
created_at: z.string().default(""),
name: z.string().default(""),
email: z.string().default(""),
diff --git a/apps/mobile/lib/comment-mention-candidates.test.ts b/apps/mobile/lib/comment-mention-candidates.test.ts
new file mode 100644
index 0000000000..d97f4456d9
--- /dev/null
+++ b/apps/mobile/lib/comment-mention-candidates.test.ts
@@ -0,0 +1,37 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { Agent, MemberWithUser, Squad } from "@multica/core/types";
+import { commentMentionCandidates } from "./comment-mention-candidates";
+
+const members = [
+ { user_id: "u-2", name: "Zoe" },
+ { user_id: "u-1", name: "Ada" },
+] as MemberWithUser[];
+const agents = [{ id: "a-1", name: "Lambda" }] as Agent[];
+const squads = [
+ { id: "s-1", name: "Relay", archived_at: null },
+ { id: "s-2", name: "Old squad", archived_at: "2026-01-01T00:00:00Z" },
+] as Squad[];
+
+describe("commentMentionCandidates", () => {
+ it("offers a member @all, people, agents and live squads, sorted", () => {
+ const result = commentMentionCandidates({ query: "", members, agents, squads, guest: false });
+
+ expect(result.all).toBe(true);
+ expect(result.members.map((m) => m.name)).toEqual(["Ada", "Zoe"]);
+ expect(result.agents.map((a) => a.id)).toEqual(["a-1"]);
+ expect(result.squads.map((s) => s.id)).toEqual(["s-1"]);
+ });
+
+ it("offers a guest people only: no @all, agents or squads (MUL-9420)", () => {
+ const result = commentMentionCandidates({ query: "", members, agents, squads, guest: true });
+
+ expect(result).toEqual({ all: false, members: [members[1], members[0]], agents: [], squads: [] });
+ });
+
+ it("filters every section by the query", () => {
+ const result = commentMentionCandidates({ query: " lam ", members, agents, squads, guest: false });
+
+ expect(result).toEqual({ all: false, members: [], agents: [agents[0]], squads: [] });
+ });
+});
diff --git a/apps/mobile/lib/comment-mention-candidates.ts b/apps/mobile/lib/comment-mention-candidates.ts
new file mode 100644
index 0000000000..de046be107
--- /dev/null
+++ b/apps/mobile/lib/comment-mention-candidates.ts
@@ -0,0 +1,43 @@
+/**
+ * The people-style rows of the comment @mention picker (`@all`, people,
+ * agents, squads), filtered by the search query and sorted by name.
+ *
+ * A guest (MUL-9420) mentions people only: the server refuses its agent and
+ * squad mentions, and it does not page the whole workspace with `@all`.
+ * Mirrors `packages/views/editor/extensions/mention-suggestion.tsx`.
+ */
+import type { Agent, MemberWithUser, Squad } from "@multica/core/types";
+
+export interface CommentMentionCandidates {
+ all: boolean;
+ members: MemberWithUser[];
+ agents: Agent[];
+ squads: Squad[];
+}
+
+export function commentMentionCandidates({
+ query,
+ members,
+ agents,
+ squads,
+ guest,
+}: {
+ query: string;
+ members: readonly MemberWithUser[];
+ agents: readonly Agent[];
+ squads: readonly Squad[];
+ guest: boolean;
+}): CommentMentionCandidates {
+ const q = query.trim().toLowerCase();
+ const matchName = (name: string) => !q || name.toLowerCase().includes(q);
+ const byName = (a: { name: string }, b: { name: string }) =>
+ a.name.localeCompare(b.name);
+ return {
+ all: !guest && (!q || "all".includes(q)),
+ members: members.filter((m) => matchName(m.name)).sort(byName),
+ agents: guest ? [] : agents.filter((a) => matchName(a.name)).sort(byName),
+ squads: guest
+ ? []
+ : squads.filter((s) => !s.archived_at && matchName(s.name)).sort(byName),
+ };
+}
diff --git a/apps/mobile/lib/member-role.test.ts b/apps/mobile/lib/member-role.test.ts
new file mode 100644
index 0000000000..fb6298717a
--- /dev/null
+++ b/apps/mobile/lib/member-role.test.ts
@@ -0,0 +1,41 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { MemberWithUser } from "@multica/core/types";
+import { isGuestRole, memberRoleOf } from "./member-role";
+
+function member(userId: string, role: MemberWithUser["role"]): MemberWithUser {
+ return {
+ id: `m-${userId}`,
+ workspace_id: "ws-1",
+ user_id: userId,
+ role,
+ created_at: "2026-01-01T00:00:00Z",
+ name: userId,
+ email: `${userId}@example.com`,
+ avatar_url: null,
+ };
+}
+
+describe("memberRoleOf", () => {
+ const members = [member("owner-1", "owner"), member("guest-1", "guest")];
+
+ it("returns the current user's role", () => {
+ expect(memberRoleOf(members, "guest-1")).toBe("guest");
+ expect(memberRoleOf(members, "owner-1")).toBe("owner");
+ });
+
+ it("is null while the list loads, signed out, or for a non-member", () => {
+ expect(memberRoleOf(undefined, "guest-1")).toBeNull();
+ expect(memberRoleOf(members, null)).toBeNull();
+ expect(memberRoleOf(members, "stranger")).toBeNull();
+ });
+});
+
+describe("isGuestRole", () => {
+ it("is true only for a guest (MUL-9420)", () => {
+ expect(isGuestRole("guest")).toBe(true);
+ for (const role of ["owner", "admin", "member", null, undefined] as const) {
+ expect(isGuestRole(role)).toBe(false);
+ }
+ });
+});
diff --git a/apps/mobile/lib/member-role.ts b/apps/mobile/lib/member-role.ts
new file mode 100644
index 0000000000..63fa712f9c
--- /dev/null
+++ b/apps/mobile/lib/member-role.ts
@@ -0,0 +1,22 @@
+/**
+ * The current user's role in a workspace, read from the cached member list.
+ * Mirrors `useCurrentMember` / `useIsGuest` in `packages/core/permissions`.
+ */
+import type { MemberRole, MemberWithUser } from "@multica/core/types";
+
+export function memberRoleOf(
+ members: readonly MemberWithUser[] | undefined,
+ userId: string | null | undefined,
+): MemberRole | null {
+ if (!members || !userId) return null;
+ return members.find((m) => m.user_id === userId)?.role ?? null;
+}
+
+/**
+ * A guest (MUL-9420) reads and comments on the issues of the projects shared
+ * with it. It cannot create issues, change their properties, or use agents,
+ * so those controls are hidden from it. False while the member list loads.
+ */
+export function isGuestRole(role: MemberRole | null | undefined): boolean {
+ return role === "guest";
+}
diff --git a/apps/mobile/lib/use-is-guest.ts b/apps/mobile/lib/use-is-guest.ts
new file mode 100644
index 0000000000..e1479054d3
--- /dev/null
+++ b/apps/mobile/lib/use-is-guest.ts
@@ -0,0 +1,13 @@
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@/data/auth-store";
+import { memberListOptions } from "@/data/queries/members";
+import { useWorkspaceStore } from "@/data/workspace-store";
+import { isGuestRole, memberRoleOf } from "@/lib/member-role";
+
+/** Whether the current user is a guest of the current workspace (MUL-9420). */
+export function useIsGuest(): boolean {
+ const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
+ const userId = useAuthStore((s) => s.user?.id ?? null);
+ const { data: members } = useQuery(memberListOptions(wsId));
+ return isGuestRole(memberRoleOf(members, userId));
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 4d935d697d..76774fb9ba 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -4022,6 +4022,13 @@ export class ApiClient {
});
}
+ async setMemberProjects(workspaceId: string, memberId: string, projectIds: string[]): Promise<MemberWithUser> {
+ return this.fetch(`/api/workspaces/${workspaceId}/members/${memberId}/projects`, {
+ method: "PUT",
+ body: JSON.stringify({ project_ids: projectIds }),
+ });
+ }
+
async deleteMember(workspaceId: string, memberId: string): Promise<void> {
await this.fetch(`/api/workspaces/${workspaceId}/members/${memberId}`, {
method: "DELETE",
diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.ts
index ce64dc85e0..8e970faa58 100644
--- a/packages/core/feature-flags/index.ts
+++ b/packages/core/feature-flags/index.ts
@@ -22,6 +22,7 @@ export {
COMPOSIO_MCP_APPS_FLAG,
DOCS_V1_FLAG,
PLUGINS_V1_FLAG,
+ WORKSPACE_GUESTS_FLAG,
} from "./keys";
export {
FeatureFlagsProvider,
diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.ts
index ba566c24af..7fc99fc905 100644
--- a/packages/core/feature-flags/keys.ts
+++ b/packages/core/feature-flags/keys.ts
@@ -3,3 +3,5 @@ export const PLUGINS_V1_FLAG = "plugins_v1";
export const DOCS_V1_FLAG = "docs_v1";
export const BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG =
"billing_workspace_subscriptions";
+// Guests (MUL-9420): free, seatless members limited to shared projects.
+export const WORKSPACE_GUESTS_FLAG = "workspace_guests";
diff --git a/packages/core/permissions/index.ts b/packages/core/permissions/index.ts
index ec535d0467..711d3c3a39 100644
--- a/packages/core/permissions/index.ts
+++ b/packages/core/permissions/index.ts
@@ -18,4 +18,4 @@ export {
useAgentPermissions,
useSkillPermissions,
} from "./use-resource-permissions";
-export { useCurrentMember } from "./use-current-member";
+export { useCurrentMember, useIsGuest } from "./use-current-member";
diff --git a/packages/core/permissions/use-current-member.ts b/packages/core/permissions/use-current-member.ts
index f8978b4ff4..8508ed4367 100644
--- a/packages/core/permissions/use-current-member.ts
+++ b/packages/core/permissions/use-current-member.ts
@@ -30,3 +30,18 @@ export function useCurrentMember(wsId: string): {
isLoading,
};
}
+
+/**
+ * Whether the current user is a guest of the workspace (MUL-9420). A guest
+ * reaches only its shared projects, so the shell hides everything else and
+ * skips the queries the server would refuse. False while the member list
+ * loads.
+ */
+export function useIsGuest(wsId: string | null | undefined): boolean {
+ const userId = useAuthStore((s) => s.user?.id ?? null);
+ const { data: members } = useQuery({
+ ...memberListOptions(wsId ?? ""),
+ enabled: !!wsId && !!userId,
+ });
+ return !!members?.some((m) => m.user_id === userId && m.role === "guest");
+}
diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsx
index 0b023fec67..3c80f020a2 100644
--- a/packages/core/realtime/provider.tsx
+++ b/packages/core/realtime/provider.tsx
@@ -9,6 +9,7 @@ import {
useSyncExternalStore,
type ReactNode,
} from "react";
+import { useQueryClient } from "@tanstack/react-query";
import { WSClient, type WSConnectionStatus } from "../api/ws-client";
import type { WSEventType, StorageAdapter } from "../types";
import type { ClientIdentity } from "../platform/types";
@@ -22,8 +23,11 @@ import {
import { useLocalSearchIndexSync } from "../search-index/hooks";
import { useGitHubConnectionStore } from "../github/connection-store";
import { createLogger } from "../logger";
+import { useIsGuest } from "../permissions/use-current-member";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
+const GUEST_REFRESH_MS = 30_000;
+
type EventHandler = (payload: unknown, actorId?: string, actorType?: string) => void;
/** `offline` means no connection is wanted: signed out or outside a workspace. */
@@ -76,6 +80,20 @@ export function WSProvider({
);
const wsId = useSyncExternalStore(subscribeToCurrentSlug, getCurrentWsId, () => null);
const [wsClient, setWsClient] = useState<WSClient | null>(null);
+ // The server streams nothing to a guest (MUL-9420), so a guest polls the
+ // queries on screen instead of holding a socket.
+ const isGuest = useIsGuest(wsId);
+ const queryClient = useQueryClient();
+ useEffect(() => {
+ if (!isGuest) return;
+ const refresh = () => void queryClient.invalidateQueries({ type: "active" });
+ const timer = window.setInterval(refresh, GUEST_REFRESH_MS);
+ window.addEventListener("focus", refresh);
+ return () => {
+ window.clearInterval(timer);
+ window.removeEventListener("focus", refresh);
+ };
+ }, [isGuest, queryClient]);
useEffect(() => () => useGitHubConnectionStore.getState().reset(), [user?.id]);
@@ -88,7 +106,7 @@ export function WSProvider({
const identityOS = identity?.os;
useEffect(() => {
- if (!user || !wsSlug) return;
+ if (!user || !wsSlug || isGuest) return;
// In token mode we need a token from storage; in cookie mode the HttpOnly
// cookie is sent automatically with the WS upgrade request.
@@ -122,6 +140,7 @@ export function WSProvider({
}, [
user,
wsSlug,
+ isGuest,
wsUrl,
storage,
cookieAuth,
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index cac27d5a5d..e3a8ec9798 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -717,10 +717,14 @@ export interface UpdateMeRequest {
export interface CreateMemberRequest {
email: string;
role?: MemberRole;
+ /** Required for a guest: the projects it can access. */
+ project_ids?: string[];
}
export interface UpdateMemberRequest {
role: MemberRole;
+ /** Required when the member becomes a guest. */
+ project_ids?: string[];
}
// Personal Access Tokens
diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.ts
index d3596a5c81..5e878e891e 100644
--- a/packages/core/types/billing.ts
+++ b/packages/core/types/billing.ts
@@ -443,7 +443,7 @@ export interface CreateWorkspaceSubscriptionPortalResponse {
* can be reduced, but nothing can be added. The server enforces on every
* write; this is only for rendering.
*/
-export type PaidFeature = "private_projects";
+export type PaidFeature = "private_projects" | "guests";
export type WorkspaceFeatureState = "available" | "locked";
diff --git a/packages/core/types/workspace.ts b/packages/core/types/workspace.ts
index d857c2dd1a..a889187e71 100644
--- a/packages/core/types/workspace.ts
+++ b/packages/core/types/workspace.ts
@@ -1,4 +1,8 @@
-export type MemberRole = "owner" | "admin" | "member";
+/**
+ * A guest (MUL-9420) sees only the projects in its `project_ids`, cannot edit
+ * issue properties or run agents, and takes no seat.
+ */
+export type MemberRole = "owner" | "admin" | "member" | "guest";
export interface WorkspaceRepo {
url: string;
@@ -104,6 +108,8 @@ export interface MemberWithUser {
name: string;
email: string;
avatar_url: string | null;
+ /** The projects a guest can access. Absent for every other role. */
+ project_ids?: string[];
}
export interface Invitation {
@@ -120,6 +126,8 @@ export interface Invitation {
inviter_name?: string;
inviter_email?: string;
workspace_name?: string;
+ /** The projects a guest invitation grants. */
+ project_ids?: string[];
}
export interface ShareLink {
diff --git a/packages/views/chat/floating-chat.tsx b/packages/views/chat/floating-chat.tsx
index 55de864ecc..819674fd88 100644
--- a/packages/views/chat/floating-chat.tsx
+++ b/packages/views/chat/floating-chat.tsx
@@ -1,7 +1,8 @@
"use client";
import { useChatStore } from "@multica/core/chat";
-import { useWorkspacePaths } from "@multica/core/paths";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { useNavigation } from "../navigation";
import { ChatFab } from "./components/chat-fab";
import { ChatWindow } from "./components/chat-window";
@@ -17,13 +18,16 @@ import { isFloatingChatRouteSuppressed } from "./floating-chat-visibility";
* 2. The Chat tab route itself. On `/:slug/chat` the full-page surface already
* owns the conversation, so a floating copy of the same `activeSessionId`
* would be pure duplication — hide it there.
+ *
+ * A guest (MUL-9420) never chats with agents, so it gets no overlay.
*/
export function FloatingChat() {
const enabled = useChatStore((s) => s.floatingChatEnabled);
const { pathname } = useNavigation();
const wsPaths = useWorkspacePaths();
+ const guest = useIsGuest(useCurrentWorkspace()?.id);
- if (!enabled) return null;
+ if (!enabled || guest) return null;
// Suppress on the Chat tab — it renders the same conversation full-page.
if (isFloatingChatRouteSuppressed(pathname, wsPaths.chat())) return null;
diff --git a/packages/views/editor/content-editor-quick-actions.test.tsx b/packages/views/editor/content-editor-quick-actions.test.tsx
index 2d50d368cd..a0fc796354 100644
--- a/packages/views/editor/content-editor-quick-actions.test.tsx
+++ b/packages/views/editor/content-editor-quick-actions.test.tsx
@@ -24,6 +24,10 @@ const listMembers = vi.hoisted(() => vi.fn());
const previewCommentTriggers = vi.hoisted(() => vi.fn());
const toastError = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("sonner", () => ({ toast: { error: toastError } }));
vi.mock("@multica/core/auth", () => ({
useAuthStore: { getState: () => ({ user: { id: "user-1" } }) },
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 2d00efdc7e..7430f2f66c 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -871,11 +871,14 @@ export function createMentionSuggestion(
const userId = useAuthStore.getState().user?.id ?? null;
const myRole =
members.find((m) => m.user_id === userId)?.role ?? null;
+ // A guest (MUL-9420) mentions people only: the server refuses agent and
+ // squad mentions from it, and it does not page the whole workspace.
+ const guest = myRole === "guest";
const q = query.toLowerCase();
const allItem: MentionItem[] =
- "all members".includes(q) || "all".includes(q)
+ !guest && ("all members".includes(q) || "all".includes(q))
? [{ id: "all", label: "All members", type: "all" as const }]
: [];
@@ -890,6 +893,7 @@ export function createMentionSuggestion(
const agentItems: MentionItem[] = agents
.filter(
(a) =>
+ !guest &&
!a.archived_at &&
(a.name.toLowerCase().includes(q) || matchesPinyin(a.name, q)) &&
canAssignAgentToIssue(a, { userId, role: myRole }).allowed,
@@ -911,6 +915,7 @@ export function createMentionSuggestion(
const squadItems: MentionItem[] = squads
.filter(
(s) =>
+ !guest &&
!s.archived_at &&
(s.name.toLowerCase().includes(q) || matchesPinyin(s.name, q)),
)
diff --git a/packages/views/issue-views/view-header.test.tsx b/packages/views/issue-views/view-header.test.tsx
index 6fa661a4d1..f58ceef783 100644
--- a/packages/views/issue-views/view-header.test.tsx
+++ b/packages/views/issue-views/view-header.test.tsx
@@ -16,8 +16,10 @@ import { IssueViewHeader } from "./view-header";
const copyLink = vi.hoisted(() => vi.fn());
const rename = vi.hoisted(() => vi.fn());
const active = vi.hoisted(() => ({ view: null as IssueView | null }));
+const viewer = vi.hoisted(() => ({ guest: false }));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/permissions", () => ({ useIsGuest: () => viewer.guest }));
vi.mock("@multica/core/paths", async (importOriginal) => {
const actual = await importOriginal<typeof import("@multica/core/paths")>();
return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
@@ -101,6 +103,7 @@ beforeEach(() => {
copyLink.mockClear();
rename.mockClear();
active.view = null;
+ viewer.guest = false;
useIssueViewRenameStore.setState({ target: null });
useIssueViewEditStore.setState({ viewId: null });
myIssuesViewStore.setState({ scope: "assigned" });
@@ -139,6 +142,19 @@ describe("IssueViewHeader copy link", () => {
});
});
+describe("IssueViewHeader new issue button", () => {
+ it("offers a member the new-issue button", () => {
+ renderHeader("my", "header-new-issue-member", adapterFor("/acme/my-issues"));
+ expect(screen.getByRole("button", { name: "New issue" })).toBeInTheDocument();
+ });
+
+ it("hides the new-issue button from a guest (MUL-9420)", () => {
+ viewer.guest = true;
+ renderHeader("my", "header-new-issue-guest", adapterFor("/acme/my-issues"));
+ expect(screen.queryByRole("button", { name: "New issue" })).toBeNull();
+ });
+});
+
describe("IssueViewHeader setup of a new view", () => {
it("opens the filter menu once the new view is named with Enter", async () => {
active.view = savedView();
diff --git a/packages/views/issue-views/view-header.tsx b/packages/views/issue-views/view-header.tsx
index 40c7aca8ff..3a177385ed 100644
--- a/packages/views/issue-views/view-header.tsx
+++ b/packages/views/issue-views/view-header.tsx
@@ -45,6 +45,7 @@ import { cn } from "@multica/ui/lib/utils";
import type { CreateIssueViewRequest, IssueView } from "@multica/core/api/schemas";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";
import type { IssueViewScope } from "@multica/core/issue-views/queries";
import {
@@ -144,6 +145,8 @@ export function IssueViewHeader({
}) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
+ // A guest (MUL-9420) cannot create issues.
+ const guest = useIsGuest(wsId);
const paths = useWorkspacePaths();
const viewScope = viewScopeOf(base);
const { activeView, setActive, missing } = useActiveIssueView(wsId, viewScope);
@@ -573,7 +576,7 @@ export function IssueViewHeader({
onTableFacetChange={controller.setActiveTableFacet}
iconOnly
/>
- {!hideCreate && (
+ {!hideCreate && !guest && (
<IconButton
label={t(($) => $.views.new_issue)}
shortcut={<ActionShortcutKeycaps action="createIssue" />}
diff --git a/packages/views/issues/components/agent-run-comment-memo.test.tsx b/packages/views/issues/components/agent-run-comment-memo.test.tsx
index 425eb0af5f..a32739d091 100644
--- a/packages/views/issues/components/agent-run-comment-memo.test.tsx
+++ b/packages/views/issues/components/agent-run-comment-memo.test.tsx
@@ -38,6 +38,13 @@ vi.mock("../../navigation", () => ({
}),
}));
+// The composer asks whether the viewer is a guest (MUL-9420); these tests
+// render as a member without an auth store.
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
+
vi.mock("@multica/core/workspace/hooks", () => ({
useActorName: () => ({ getActorName: () => "Ada" }),
}));
diff --git a/packages/views/issues/components/annotation-reply-interactions.test.tsx b/packages/views/issues/components/annotation-reply-interactions.test.tsx
index 76f56abfaa..1ad2a88a09 100644
--- a/packages/views/issues/components/annotation-reply-interactions.test.tsx
+++ b/packages/views/issues/components/annotation-reply-interactions.test.tsx
@@ -14,6 +14,10 @@ import { ReplyInput } from "./reply-input";
import { CommentInput } from "./comment-input";
// Avatar profile navigation is unrelated to composer behavior.
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null, AgentStatusDot: () => null }));
const preview = vi.hoisted(() => vi.fn<typeof import("@multica/core/api")["api"]["previewCommentTriggers"]>(async () => ({ agents: [], blocked: [] })));
diff --git a/packages/views/issues/components/comment-card-actions-menu.test.tsx b/packages/views/issues/components/comment-card-actions-menu.test.tsx
index eb9ad737c6..42b0517931 100644
--- a/packages/views/issues/components/comment-card-actions-menu.test.tsx
+++ b/packages/views/issues/components/comment-card-actions-menu.test.tsx
@@ -10,6 +10,10 @@ import { renderWithI18n } from "../../test/i18n";
// Copy link), and Delete alone at the bottom. Edit and Delete only show on
// comments the viewer may change.
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/api", () => ({
api: { uploadFile: vi.fn() },
dispatchReasonCode: () => undefined,
@@ -77,7 +81,7 @@ function comment(
function renderThread(
root: TimelineEntry,
replies: TimelineEntry[],
- { resolvable = true }: { resolvable?: boolean } = {},
+ { resolvable = true, canCreateSubIssue = true }: { resolvable?: boolean; canCreateSubIssue?: boolean } = {},
) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return renderWithI18n(
@@ -92,7 +96,7 @@ function renderThread(
onDelete={vi.fn()}
onToggleReaction={vi.fn()}
onCopyLink={vi.fn()}
- onCreateSubIssue={vi.fn()}
+ onCreateSubIssue={canCreateSubIssue ? vi.fn() : undefined}
onResolveToggle={resolvable ? vi.fn() : undefined}
/>
</QueryClientProvider>,
@@ -166,6 +170,41 @@ describe("CommentCard — actions menu layout", () => {
]);
});
+ // A guest (MUL-9420) is never a moderator and cannot create issues, so the
+ // issue page passes canModerate=false and no onCreateSubIssue.
+ it("gives a guest Edit and Delete on its own comment, without Create sub-issue", async () => {
+ renderThread(comment("root", null), [], { canCreateSubIssue: false });
+
+ expect(await openMenuLayout(0)).toEqual([
+ "Reply",
+ "Add reaction",
+ "Edit",
+ SEPARATOR,
+ "Resolve thread",
+ SEPARATOR,
+ "Copy",
+ "Copy link",
+ SEPARATOR,
+ "Delete",
+ ]);
+ });
+
+ it("gives a guest no Edit or Delete on another member's comment", async () => {
+ renderThread(comment("root", null, { actor_type: "member", actor_id: "user-2" }), [], {
+ canCreateSubIssue: false,
+ });
+
+ expect(await openMenuLayout(0)).toEqual([
+ "Reply",
+ "Add reaction",
+ SEPARATOR,
+ "Resolve thread",
+ SEPARATOR,
+ "Copy",
+ "Copy link",
+ ]);
+ });
+
it("keeps Create sub-issue when the thread cannot be resolved", async () => {
renderThread(comment("root", null, agentAuthor), [], { resolvable: false });
diff --git a/packages/views/issues/components/comment-card-copy-link.test.tsx b/packages/views/issues/components/comment-card-copy-link.test.tsx
index f0c9337faf..c9e3d720ac 100644
--- a/packages/views/issues/components/comment-card-copy-link.test.tsx
+++ b/packages/views/issues/components/comment-card-copy-link.test.tsx
@@ -10,6 +10,10 @@ import { renderWithI18n } from "../../test/i18n";
// `useIssueActions.copyCommentLink`; this suite pins that the card routes each
// row's own id to the handler and hides the item when no handler is wired.
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/api", () => ({
api: { uploadFile: vi.fn() },
dispatchReasonCode: () => undefined,
diff --git a/packages/views/issues/components/comment-card-deleted.test.tsx b/packages/views/issues/components/comment-card-deleted.test.tsx
index 77a02910b0..eb24475430 100644
--- a/packages/views/issues/components/comment-card-deleted.test.tsx
+++ b/packages/views/issues/components/comment-card-deleted.test.tsx
@@ -11,6 +11,10 @@ import { renderWithI18n } from "../../test/i18n";
// tombstoned ROOT keeps a placeholder, since it heads the thread. The cache
// rules live in packages/core/issues/comment-deletion.test.ts.
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/api", () => ({
api: { uploadFile: vi.fn() },
dispatchReasonCode: () => undefined,
diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsx
index 9ef8fad7ab..d79d43f0d0 100644
--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx
+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx
@@ -18,6 +18,10 @@ const editorDefaultValues = vi.hoisted(() => ({
// the same or the two records drift apart only in tests.
let mockUploadIdSeq = 0;
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/api", () => ({
// Uploads flow through the coordinator, which calls api.uploadFile (MUL-5181).
api: { uploadFile: apiUploadFile },
diff --git a/packages/views/issues/components/comment-card-virtual-rows.test.tsx b/packages/views/issues/components/comment-card-virtual-rows.test.tsx
index 8f5260b566..265c2187ee 100644
--- a/packages/views/issues/components/comment-card-virtual-rows.test.tsx
+++ b/packages/views/issues/components/comment-card-virtual-rows.test.tsx
@@ -24,6 +24,13 @@ vi.mock("../../navigation", () => ({
}),
}));
+// The composer asks whether the viewer is a guest (MUL-9420); these tests
+// render as a member without an auth store.
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
+
vi.mock("@multica/core/workspace/hooks", () => ({
useActorName: () => ({ getActorName: () => "Ada" }),
}));
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 9983382fc2..72b016f993 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -67,6 +67,10 @@ const editorUploadSignal = vi.hoisted(
// the same or the two records drift apart only in tests.
let mockUploadIdSeq = 0;
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/api", () => ({
api: {
getBaseUrl: () => "https://api.example.test",
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 62ba7d2fad..f3d6fa0bec 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -2,6 +2,9 @@
import { useRef, useState, useEffect, useMemo } from "react";
import { cn } from "@multica/ui/lib/utils";
+import { Info } from "@multica/ui/icons";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { Button } from "@multica/ui/components/ui/button";
@@ -57,6 +60,9 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const editorRef = useRef<ContentEditorRef>(null);
+ // A guest (MUL-9420) comments and mentions people, nothing that runs agents.
+ const guest = useIsGuest(useCurrentWorkspace()?.id);
+ const placeholder = guest ? t(($) => $.comment.guest_placeholder) : t(($) => $.comment.leave_comment_placeholder);
// Sending mid-upload would strip the pending image's blob URL out of the
// markdown and bind no attachment id — the comment posts without the file.
const uploadGate = useUploadGate(editorRef);
@@ -291,7 +297,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
ref={editorRef}
value={persistedDraft ?? content}
onReady={lazy.onReady}
- placeholder={t(($) => $.comment.leave_comment_placeholder)}
+ placeholder={placeholder}
onUpdate={(md) => {
setContent(md);
setIsEmpty(!md.trim());
@@ -307,7 +313,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
debounceMs={100}
currentIssueId={issueId}
attachments={pendingAttachments}
- enableSlashCommands
+ enableSlashCommands={!guest}
slashCommandMode="command"
quickActionMenu={quickActionMenu}
/>
@@ -321,7 +327,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
data-testid="comment-composer-shell"
role="button"
tabIndex={0}
- aria-label={t(($) => $.comment.leave_comment_placeholder)}
+ aria-label={placeholder}
className="flex-1 min-h-0 cursor-text px-3 py-2"
onClick={() => lazy.activate()}
onKeyDown={(e) => {
@@ -335,7 +341,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
exact type metrics (line-height 1.625 from prose.css), so the
shell→editor swap doesn't shift layout. */}
<div className="rich-text-editor text-body">
- <p className="text-muted-foreground">{t(($) => $.comment.leave_comment_placeholder)}</p>
+ <p className="text-muted-foreground">{placeholder}</p>
</div>
</div>
)}
@@ -345,15 +351,20 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
<ComposerToolbar
className="px-1.5 pb-1"
voice={voice}
- hasRecipients={showsTriggerChips}
- recipients={<CommentTriggerChips
+ hasRecipients={guest || showsTriggerChips}
+ recipients={guest ? (
+ <p className="flex items-center gap-1.5 px-1.5 text-caption text-muted-foreground">
+ <Info className="size-3.5 shrink-0" aria-hidden="true" />
+ <span className="truncate">{t(($) => $.comment.guest_hint)}</span>
+ </p>
+ ) : <CommentTriggerChips
recipients={recipients}
blocked={triggerPreview.blocked}
hasAllMembersMention={triggerPreview.hasAllMembersMention}
draftContent={composedContent}
onActionChange={setAction}
/>}
- tools={<ComposerTools voice={voice} onAttach={(file) => lazy.uploadOrQueue([file])} />}
+ tools={guest ? null : <ComposerTools voice={voice} onAttach={(file) => lazy.uploadOrQueue([file])} />}
send={routing.restartTaskIds.length > 0 ? (
<Button
size="sm"
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 50e0815b71..3f9d141fc3 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -28,6 +28,7 @@ import {
CircleCheck,
FileQuestion,
Loader2,
+ Lock,
Milestone,
MoreHorizontal,
PanelRight,
@@ -47,7 +48,7 @@ import { IconButton } from "@multica/ui/components/common/icon-button";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";
import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
-import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence } from "../../editor";
+import { ContentEditor, ReadonlyContent, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence } from "../../editor";
import {
WAKEUP_ACTIVITY_ACTIONS,
WakeupActivityIcon,
@@ -80,6 +81,7 @@ import { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";
import { UnsubscribeArchiveButton } from "../../inbox/components/unsubscribe-archive-button";
import type { InboxUnsubscribeScope } from "@multica/core/inbox/mutations";
import { PropRow } from "../../common/prop-row";
+import { useIsGuest } from "@multica/core/permissions";
import { TimelineHandoff } from "../../workflows/timeline-handoff";
import { PropertyIcon } from "../../common/property-icon";
import type { Attachment, Issue, IssueProperty, IssueStatus, IssueStatusCategory, IssuePriority, TimelineEntry, UpdateIssueRequest } from "@multica/core/types";
@@ -567,6 +569,9 @@ const EMPTY_REPLIES: TimelineEntry[] = [];
// its row and add-property entry are gated on `issue.parent_issue_id` at the
// render site below — it stays in this list so seeding/visibility flow through
// the same machinery as the other optional props.
+/** The sidebar sections a guest gets: read-only facts about the issue itself. */
+const GUEST_SIDEBAR_SECTIONS = new Set<IssueSidebarSection>(["properties", "parent", "deliverables"]);
+
const OPTIONAL_PROP_KEYS = ["priority", "stage", "start_date", "due_date", "labels"] as const;
type OptionalPropKey = (typeof OPTIONAL_PROP_KEYS)[number];
@@ -1533,6 +1538,8 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
const wsId = useWorkspaceId();
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ // A guest (MUL-9420) reads and comments; it edits nothing and sees no runs.
+ const guest = useIsGuest(wsId);
// Workspace owners and admins moderate any comment authored by anyone
// (mirrors backend `comment.go:507-512`). Computed here so per-comment
// rendering doesn't have to re-derive it for every row.
@@ -1913,7 +1920,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
editComment, deleteComment, toggleResolveComment, toggleReaction: handleToggleReaction,
} = useIssueTimeline(id, user?.id, activeDeliverableJump?.commentId);
- const { data: commentTasks, isLoading: commentTasksLoading } = useQuery(issueTasksOptions(id));
+ const { data: commentTasks, isLoading: commentTasksLoading } = useQuery({ ...issueTasksOptions(id), enabled: !guest });
// Only a landing on data already in hand is worth holding the chrome for;
// while the timeline is still on its way, the chrome renders in the wait.
useEffect(() => {
@@ -3323,8 +3330,44 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
</div>
);
+ const locked = (value: ReactNode) => (
+ <>
+ <div inert className="flex min-w-0 flex-1 items-center">{value}</div>
+ <Lock className="size-3 shrink-0 text-faint-foreground" aria-hidden="true" />
+ </>
+ );
+ const guestProperties = (
+ <div>
+ <IssueSidebarSectionHeader title={t(($) => $.detail.section_properties)} open={propertiesOpen} onOpenChange={setPropertiesOpen} />
+ {propertiesOpen && (
+ <>
+ <IssueSidebarPropertyGrid>
+ <PropRow interactive={false} label={t(($) => $.detail.prop_status)}>
+ {locked(<StatusPicker status={issue.status} onUpdate={handleUpdateField} align="start" projectId={issue.project_id} issue={issue} />)}
+ </PropRow>
+ <PropRow interactive={false} label={t(($) => $.detail.prop_assignee)}>
+ {locked(<AssigneePicker assigneeType={issue.assignee_type} assigneeId={issue.assignee_id} onUpdate={handleUpdateField} align="start" />)}
+ </PropRow>
+ <PropRow interactive={false} label={t(($) => $.detail.prop_priority)}>
+ {locked(<PriorityPicker priority={issue.priority} onUpdate={handleUpdateField} align="start" />)}
+ </PropRow>
+ <PropRow interactive={false} label={t(($) => $.detail.prop_project)}>
+ {locked(<IssueProjectPicker projectId={issue.project_id} onUpdate={handleUpdateField} issue={issue} />)}
+ </PropRow>
+ {attachedLabels.length > 0 && (
+ <PropRow interactive={false} label={t(($) => $.detail.prop_labels)}>
+ {locked(<LabelPicker issueId={issue.id} align="start" />)}
+ </PropRow>
+ )}
+ </IssueSidebarPropertyGrid>
+ <p className="px-4 pt-2 text-caption text-muted-foreground">{t(($) => $.detail.guest_readonly_note)}</p>
+ </>
+ )}
+ </div>
+ );
+
const sidebarSections: Record<IssueSidebarSection, ReactNode> = {
- properties: (
+ properties: guest ? guestProperties : (
<div>
<IssueSidebarSectionHeader title={t(($) => $.detail.section_properties)} open={propertiesOpen} onOpenChange={setPropertiesOpen} />
{propertiesOpen && <IssueSidebarPropertyGrid>
@@ -3619,7 +3662,10 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
<IssueSidebarSections
sections={sidebarSections}
available={ISSUE_SIDEBAR_SECTIONS.filter(
- (section) => (section !== "pull_requests" || githubSettings.prSidebar) && (section !== "plugins" || pluginsEnabled),
+ (section) =>
+ guest
+ ? GUEST_SIDEBAR_SECTIONS.has(section)
+ : (section !== "pull_requests" || githubSettings.prSidebar) && (section !== "plugins" || pluginsEnabled),
)}
revealed={revealedWakeupsFor === id ? REVEALED_WAKEUPS : undefined}
onRevealEnd={() => setRevealedWakeupsFor(null)}
@@ -3642,7 +3688,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
issueId: id, replyScrollParent: scrollContainerEl, entry: reply, replies: timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES,
currentUserId: user?.id, canModerate: canModerateComments, onReply: submitReply,
onReplyAccepted: scrollToTimelineBottom, onEdit: editComment, onDelete: deleteComment,
- onToggleReaction: handleToggleReaction, onCreateSubIssue: openCommentSubIssue,
+ onToggleReaction: handleToggleReaction, onCreateSubIssue: guest ? undefined : openCommentSubIssue,
onResolveToggle: handleResolveToggle,
onCopyLink: actions.copyCommentLink, onJumpToComment: jumpToComment,
onCollapseResolved: reply.resolved_at ? () => toggleResolvedExpand(reply.id, false) : undefined,
@@ -3681,7 +3727,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
onEdit={editComment}
onDelete={deleteComment}
onToggleReaction={handleToggleReaction}
- onCreateSubIssue={openCommentSubIssue}
+ onCreateSubIssue={guest ? undefined : openCommentSubIssue}
onResolveToggle={handleResolveToggle}
onCopyLink={actions.copyCommentLink}
onJumpToComment={jumpToComment}
@@ -3798,8 +3844,8 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
{/* Live "agent is working" chip, leftmost in the right cluster so
it never overlaps the title (which truncates to make room).
It self-hides when no agent is active. */}
- <IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} />
- <IssueWakeupHeaderChip issueId={id} onOpen={openWakeups} />
+ {!guest && <IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} />}
+ {!guest && <IssueWakeupHeaderChip issueId={id} onOpen={openWakeups} />}
{!onDone && !isPeek && (
<IssueInboxActions
issueId={id}
@@ -3841,7 +3887,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
>
{actions.isPinned ? <PinOff /> : <Pin />}
</IconButton>
- <IssueDetailActionsDropdown
+ {!guest && <IssueDetailActionsDropdown
issue={issue}
locateInSidebar={!isPeek}
align="end"
@@ -3860,7 +3906,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
<MoreHorizontal />
</IconButton>
}
- />
+ />}
{isPeek ? (
trailingActions
) : (
@@ -3918,7 +3964,8 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
/>
<div id={descriptionSectionId}>
<div data-mc="issue-title">
- {titleLazy.active && (
+ {guest && <div className={cn("w-full leading-snug", titleSizeClass)}>{issue.title}</div>}
+ {!guest && titleLazy.active && (
<div className={titleLazy.ready ? undefined : "hidden"}>
<TitleEditor
key={`title-${id}-${titleResetToken}`}
@@ -3949,7 +3996,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
/>
</div>
)}
- {!titleLazy.ready && (
+ {!guest && !titleLazy.ready && (
<div
role="button"
tabIndex={0}
@@ -4083,7 +4130,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
)}
<div
- {...descDropZoneProps}
+ {...(guest ? {} : descDropZoneProps)}
{...descriptionAnnotations.captureProps}
ref={descriptionAnnotations.cardRef}
className="relative mt-5 rounded-lg"
@@ -4100,6 +4147,9 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
>
{descriptionAnnotations.popup}
<div data-comment-content={descriptionSourceId}>
+ {guest ? (
+ <ReadonlyContent content={issue.description ?? ""} attachments={descEditorAttachments} />
+ ) : (
<ContentEditor
ref={descEditorRef}
key={id}
@@ -4142,6 +4192,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
selectionAction={descriptionSelectionAction}
attachments={descEditorAttachments}
/>
+ )}
</div>
<div className="flex items-center gap-1 mt-3">
@@ -4151,11 +4202,13 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
onToggle={handleToggleIssueReaction}
getActorName={getActorName}
/>
- <FileUploadButton
- size="sm"
- multiple
- onSelect={(file) => descEditorRef.current?.uploadFile(file)}
- />
+ {!guest && (
+ <FileUploadButton
+ size="sm"
+ multiple
+ onSelect={(file) => descEditorRef.current?.uploadFile(file)}
+ />
+ )}
</div>
{descDragOver && <FileDropOverlay />}
</div>
@@ -4163,7 +4216,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
</div>
{/* Sub-issues — Linear-style */}
- {childIssues.length === 0 && (
+ {childIssues.length === 0 && !guest && (
<div className="mt-6">
<button
type="button"
@@ -4205,8 +4258,8 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
</div>
{/* issue.id, not the route param — the endpoint takes a
UUID and the route may carry a human-readable id. */}
- <SubIssuesAgentWorkingChip parentIssueId={issue.id} />
- <input
+ {!guest && <SubIssuesAgentWorkingChip parentIssueId={issue.id} />}
+ {!guest && <input
type="checkbox"
checked={allChildrenSelected}
ref={(el) => {
@@ -4220,10 +4273,10 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
? "opacity-100"
: "opacity-0 group-hover/sub-issues:opacity-100 focus-visible:opacity-100",
)}
- />
+ />}
<div className="ml-auto flex items-center gap-0.5">
<SubIssueDisplayPopover workspaceProperties={activeWorkspaceProperties} />
- <Tooltip>
+ {!guest && <Tooltip>
<TooltipTrigger
render={
<button
@@ -4237,7 +4290,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
}
/>
<TooltipContent side="bottom">{t(($) => $.detail.add_sub_issue_tooltip)}</TooltipContent>
- </Tooltip>
+ </Tooltip>}
</div>
</div>
diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsx
index 32f90e2523..e5722bfd2b 100644
--- a/packages/views/issues/components/issues-page.tsx
+++ b/packages/views/issues/components/issues-page.tsx
@@ -36,13 +36,13 @@ function IssuesSurfacePage() {
modes={["board", "list", "table", "swimlane"]}
batchToolbar="list"
renderHeader={({ controller }) => <IssueViewHeader controller={controller} base={WORKSPACE_BASE} />}
- renderEmpty={({ controller }) => (
+ renderEmpty={({ controller, canCreate }) => (
<CollectionPageState
icon={ListTodo}
title={t(($) => $.page.empty_title)}
description={t(($) => $.page.empty_description)}
actions={
- <>
+ canCreate && <>
<Button size="sm" onClick={() => controller.openCreateIssue()}>
<Plus aria-hidden="true" />
{t(($) => $.views.new_issue)}
diff --git a/packages/views/issues/components/table-view-editing.test.tsx b/packages/views/issues/components/table-view-editing.test.tsx
index 922689df6a..17d9312421 100644
--- a/packages/views/issues/components/table-view-editing.test.tsx
+++ b/packages/views/issues/components/table-view-editing.test.tsx
@@ -208,10 +208,12 @@ function Harness({
childProgressMap,
surfaceKey,
onCreateIssue = () => {},
+ canCreate = true,
}: {
childProgressMap: Map<string, ChildProgress>;
surfaceKey: string;
onCreateIssue?: (defaults: IssueCreateDefaults) => void;
+ canCreate?: boolean;
}) {
return (
<ViewStoreProvider store={getIssueSurfaceViewStore(surfaceKey)}>
@@ -222,7 +224,7 @@ function Harness({
search=""
onSearchChange={() => {}}
onLoadedIssuesChange={() => {}}
- onCreateIssue={onCreateIssue}
+ onCreateIssue={canCreate ? onCreateIssue : undefined}
exportIssues={() => Promise.resolve(serverIssues)}
resolveExportLookups={() =>
Promise.resolve({
@@ -435,6 +437,25 @@ describe("TableView cell editors under data refresh", () => {
});
});
+ it("offers no sub-issue creation when the viewer cannot create issues (guest, MUL-9420)", async () => {
+ serverIssues = [makeIssue("a", "Alpha task", "todo")];
+
+ renderWithI18n(
+ <QueryClientProvider client={queryClient}>
+ <Harness
+ childProgressMap={new Map()}
+ surfaceKey={`test-no-sub-issue-${Math.floor(Math.random() * 1e9)}`}
+ canCreate={false}
+ />
+ </QueryClientProvider>,
+ );
+
+ const row = (await screen.findByText("MUL-a")).closest("tr")!;
+ expect(within(row).queryByRole("button", { name: "Create sub-issue" })).toBeNull();
+ // The row's other title action stays.
+ expect(within(row).getByRole("button", { name: "Rename issue" })).toBeInTheDocument();
+ });
+
it("uses the preferred peek for both titles and row space; Shift opens the full page instead", async () => {
useIssueOpeningStore.getState().setOpenMode("peek");
serverIssues = [makeIssue("a", "Alpha task", "todo")];
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index c1aab9d7db..a0b95d10bc 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -183,7 +183,9 @@ type TableViewProps = {
search: string;
onSearchChange: (query: string) => void;
onLoadedIssuesChange: (issues: Issue[]) => void;
- onCreateIssue: (defaults: IssueCreateDefaults) => void;
+ /** Omitted when the viewer cannot create issues: the row's add-sub-issue
+ * button goes with it. */
+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;
exportIssues: () => Promise<Issue[]>;
resolveExportLookups: (needs: {
projects: boolean;
@@ -671,7 +673,8 @@ export function InlineTitle({
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
/** Navigate to the issue — clicking the title is the primary way IN. */
onOpen: (event: React.MouseEvent) => void;
- onCreateSubIssue: () => void;
+ /** Omitted when the viewer cannot create issues. */
+ onCreateSubIssue?: () => void;
onToggleParent: () => void;
toggleLabel: string;
renameLabel: string;
@@ -800,23 +803,25 @@ export function InlineTitle({
* follows the row's hover colour, since that is what the cell is
* painted with when they appear. */}
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center gap-0.5 bg-gradient-to-l from-background from-70% to-transparent pr-1 pl-8 opacity-0 transition-opacity group-hover:from-[color-mix(in_oklab,var(--muted)_50%,var(--background))] group-hover/title:pointer-events-auto group-hover/title:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100">
- <DeferredTooltip
- content={createSubIssueLabel}
- trigger={
- <button
- type="button"
- aria-label={createSubIssueLabel}
- className="rounded-xs p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
- onClick={(event) => {
- event.stopPropagation();
- onCreateSubIssue();
- }}
- onAuxClick={stopRowNavigation}
- >
- <Plus className="size-3" />
- </button>
- }
- />
+ {onCreateSubIssue && (
+ <DeferredTooltip
+ content={createSubIssueLabel}
+ trigger={
+ <button
+ type="button"
+ aria-label={createSubIssueLabel}
+ className="rounded-xs p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
+ onClick={(event) => {
+ event.stopPropagation();
+ onCreateSubIssue();
+ }}
+ onAuxClick={stopRowNavigation}
+ >
+ <Plus className="size-3" />
+ </button>
+ }
+ />
+ )}
<DeferredTooltip
content={renameLabel}
trigger={
@@ -991,7 +996,7 @@ type TableViewMeta = {
* category and owner to decide whether the write needs confirming first. */
updateIssue: (issue: Issue, updates: Partial<UpdateIssueRequest>) => void;
openIssue: (issue: Issue, event?: React.MouseEvent) => void;
- createSubIssue: (issue: Issue) => void;
+ createSubIssue: ((issue: Issue) => void) | undefined;
toggleTableParentCollapsed: (issueId: string) => void;
handleIssueSelection: (issueId: string, shiftKey: boolean) => void;
getActorName: (actorType: string, actorId: string) => string;
@@ -1191,7 +1196,7 @@ function IssueTableBodyCell({
onEditingChange={setEditorOpen}
onUpdate={onUpdate}
onOpen={(event) => meta.openIssue(issue, event)}
- onCreateSubIssue={() => meta.createSubIssue(issue)}
+ onCreateSubIssue={meta.createSubIssue && (() => meta.createSubIssue?.(issue))}
onToggleParent={() => meta.toggleTableParentCollapsed(issue.id)}
toggleLabel={t(($) => $.table.toggle_sub_issues)}
renameLabel={t(($) => $.table.rename_title)}
@@ -2236,9 +2241,11 @@ export function TableView({
[intentNavigate, paths, handlePeekClick],
);
- const createSubIssue = useCallback(
- (issue: Issue) =>
- onCreateIssue(subIssueCreateDefaults(issue)),
+ const createSubIssue = useMemo(
+ () =>
+ onCreateIssue
+ ? (issue: Issue) => onCreateIssue(subIssueCreateDefaults(issue))
+ : undefined,
[onCreateIssue],
);
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
index 165f800815..83b3193071 100644
--- a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
@@ -10,6 +10,10 @@ import {
useCommentTriggerPreview,
} from "./use-comment-trigger-preview";
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/api", () => ({
api: {
previewCommentTriggers: vi.fn(),
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.ts b/packages/views/issues/hooks/use-comment-trigger-preview.ts
index 380885fc34..adfd9b2d2c 100644
--- a/packages/views/issues/hooks/use-comment-trigger-preview.ts
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.ts
@@ -5,6 +5,8 @@ import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { api } from "@multica/core/api";
import { issueKeys } from "@multica/core/issues/queries";
import { parseMentions } from "@multica/core/issues/comment-trigger-outcomes";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import type { CommentTriggerPreviewAgent, CommentTriggerOutcome } from "@multica/core/types";
const COMMENT_TRIGGER_PREVIEW_DEBOUNCE_MS = 300;
@@ -98,6 +100,9 @@ export function useCommentTriggerPreview({
[content],
);
const debouncedSignature = useDebouncedSignature(signature);
+ // A guest's comment never starts an agent (MUL-9420), so there is nothing
+ // to preview and the server refuses the request.
+ const guest = useIsGuest(useCurrentWorkspace()?.id);
const contentRef = useRef(content);
const parentKey = parentId ?? "";
const editingKey = editingCommentId ?? "";
@@ -109,7 +114,7 @@ export function useCommentTriggerPreview({
const previewQuery = useQuery({
queryKey: [...issueKeys.commentTriggerPreview(issueId), parentKey, editingKey, debouncedSignature],
queryFn: () => api.previewCommentTriggers(issueId, contentRef.current, parentId, editingCommentId),
- enabled: signature !== "empty" && debouncedSignature !== "empty",
+ enabled: !guest && signature !== "empty" && debouncedSignature !== "empty",
retry: false,
// The answer depends on live queue state (pending-task dedup), not just
// the mention set, so a cached result must revalidate when its signature
diff --git a/packages/views/issues/hooks/use-quick-action-menu.ts b/packages/views/issues/hooks/use-quick-action-menu.ts
index aaba7f0e39..aad9d699cb 100644
--- a/packages/views/issues/hooks/use-quick-action-menu.ts
+++ b/packages/views/issues/hooks/use-quick-action-menu.ts
@@ -7,7 +7,7 @@ import type { Editor } from "@tiptap/core";
import type { Node } from "@tiptap/pm/model";
import { useAuthStore } from "@multica/core/auth";
import { useCurrentWorkspace } from "@multica/core/paths";
-import { canAssignAgentToIssue } from "@multica/core/permissions";
+import { canAssignAgentToIssue, useIsGuest } from "@multica/core/permissions";
import { isDeletedComment } from "@multica/core/issues/comment-deletion";
import { parseMentions } from "@multica/core/issues/comment-trigger-outcomes";
import { issueDetailOptions, issueKeys } from "@multica/core/issues/queries";
@@ -191,10 +191,12 @@ export function useQuickActionMenu(
const queryClient = useQueryClient();
const workspace = useCurrentWorkspace();
const wsId = workspace?.id ?? "";
- const hasIssueContext = enabled && wsId !== "" && !!issueId;
+ // Quick actions run agents, which a guest (MUL-9420) cannot.
+ const guest = useIsGuest(wsId);
+ const hasIssueContext = enabled && wsId !== "" && !!issueId && !guest;
const { data } = useQuery({
...quickActionListOptions(wsId),
- enabled: enabled && wsId !== "",
+ enabled: enabled && wsId !== "" && !guest,
});
const { data: issue } = useQuery({
...issueDetailOptions(wsId, issueId ?? ""),
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index b507a036bb..590fe1fbd0 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -30,6 +30,7 @@ import { createIssueStatusListStore } from "@multica/core/issue-statuses";
import { baselineFromQuery } from "@multica/core/issue-views/baseline";
import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
import { setCurrentWorkspace } from "@multica/core/platform";
+import { memberListOptions } from "@multica/core/workspace/queries";
import { statusTableMethodsFromLegacy } from "./status-table-test-api";
// Mutable so tests can simulate a workspace switch — the workspace layout
@@ -1146,3 +1147,127 @@ describe("IssueSurface — status catalog failure", () => {
expect(rowRequests.length).toBeGreaterThanOrEqual(before);
});
});
+
+describe("IssueSurface — guest create affordances (MUL-9420)", () => {
+ let qc: QueryClient;
+
+ function seedRole(role: "member" | "guest") {
+ qc.setQueryData(memberListOptions("ws-1").queryKey, [
+ {
+ id: "m-1",
+ workspace_id: "ws-1",
+ user_id: mockAuthUser.id,
+ role,
+ created_at: "2026-01-01T00:00:00Z",
+ name: mockAuthUser.name,
+ email: mockAuthUser.email,
+ avatar_url: null,
+ },
+ ]);
+ }
+
+ function useIssues(issues: Issue[]) {
+ const listIssues = vi.fn((params?: ListIssuesParams) => {
+ const rows = params?.status === "todo" ? issues : [];
+ return Promise.resolve({ issues: rows, total: rows.length } satisfies ListIssuesResponse);
+ });
+ setApiInstance({
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
+ listIssues,
+ ...statusTableMethodsFromLegacy(listIssues),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => never()),
+ listMembers: vi.fn(() => never()),
+ getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),
+ getWorkspaceWorkingAgents: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => never()),
+ listIssueUnread: vi.fn(() => Promise.resolve([])),
+ listSubscribedIssueIds: vi.fn(() => Promise.resolve([])),
+ listIssueViews: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+ }
+
+ beforeEach(() => {
+ mockWsId.current = "ws-1";
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ // Resolve `t(($) => $.a.b)` to "a.b" so controls can be found by key.
+ mockTranslate.mockImplementation(((...args: unknown[]) => {
+ const path: string[] = [];
+ const probe: unknown = new Proxy(() => {}, {
+ get: (_target, property) => {
+ path.push(String(property));
+ return probe;
+ },
+ });
+ (args[0] as (value: unknown) => unknown)(probe);
+ return path.join(".");
+ }) as unknown as () => string);
+ pruneIssueSurfaceViewStates([]);
+ });
+
+ afterEach(() => {
+ cleanup();
+ qc.clear();
+ pruneIssueSurfaceViewStates([]);
+ mockTranslate.mockImplementation(() => "translated");
+ vi.restoreAllMocks();
+ });
+
+ function surface(renderEmpty?: (context: { canCreate: boolean }) => React.ReactNode) {
+ return (
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "pg" }}
+ modes={["list"]}
+ renderHeader={() => null}
+ renderEmpty={renderEmpty}
+ batchToolbar="never"
+ />
+ </QueryClientProvider>
+ );
+ }
+
+ it("offers a member the empty state's create actions", async () => {
+ useIssues([]);
+ seedRole("member");
+ render(surface());
+
+ await screen.findByText("detail.empty_issues_title");
+ expect(screen.getByRole("button", { name: "detail.empty_issues_new_button" })).toBeInTheDocument();
+ });
+
+ it("drops the empty state's create actions for a guest", async () => {
+ useIssues([]);
+ seedRole("guest");
+ render(surface());
+
+ await screen.findByText("detail.empty_issues_title");
+ expect(screen.queryByRole("button", { name: "detail.empty_issues_new_button" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "detail.empty_issues_add_existing" })).toBeNull();
+ });
+
+ it("tells a page's own empty state that a guest cannot create", async () => {
+ useIssues([]);
+ seedRole("guest");
+ const renderEmpty = vi.fn(({ canCreate }: { canCreate: boolean }) => (
+ <div data-testid="custom-empty">{String(canCreate)}</div>
+ ));
+ render(surface(renderEmpty));
+
+ expect(await screen.findByTestId("custom-empty")).toHaveTextContent("false");
+ });
+
+ it("hides the list group's add-issue button from a guest only", async () => {
+ useIssues([makeIssue("g1", "Guest-visible issue", "pg")]);
+ seedRole("member");
+ const { unmount } = render(surface());
+ await screen.findByText("Guest-visible issue");
+ expect(screen.getAllByRole("button", { name: "list.add_issue_tooltip" }).length).toBeGreaterThan(0);
+ unmount();
+
+ seedRole("guest");
+ render(surface());
+ await screen.findByText("Guest-visible issue");
+ expect(screen.queryByRole("button", { name: "list.add_issue_tooltip" })).toBeNull();
+ });
+});
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index 289b299848..c9753ad3f4 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -10,6 +10,7 @@ import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspaceId } from "@multica/core/hooks";
import { useModalStore } from "@multica/core/modals";
+import { useIsGuest } from "@multica/core/permissions";
import { useQuery } from "@tanstack/react-query";
import { workspaceWakeupSummariesOptions } from "@multica/core/issues/wakeups";
import {
@@ -60,6 +61,8 @@ import {
export interface IssueSurfaceRenderContext {
controller: IssueSurfaceController;
issues: Issue[];
+ /** Whether the viewer may create issues here; false for a guest (MUL-9420). */
+ canCreate: boolean;
}
interface IssueSurfaceComponentProps extends IssueSurfaceProps {
@@ -243,6 +246,9 @@ function IssueSurfaceContent({
contentClassName,
}: Omit<IssueSurfaceComponentProps, "surfaceKey">) {
const workspaceId = useWorkspaceId();
+ // A guest (MUL-9420) cannot create issues anywhere, sub-issues included.
+ const guest = useIsGuest(workspaceId);
+ const canCreate = allowCreate && !guest;
// One polling owner for the whole surface; individual cards only select cache data.
useQuery({ ...workspaceWakeupSummariesOptions(workspaceId), refetchInterval: 10_000 });
const { t } = useT("projects");
@@ -279,8 +285,8 @@ function IssueSurfaceContent({
[clientFilter, controller.swimlaneIssues],
);
const renderContext = useMemo(
- () => ({ controller, issues }),
- [controller, issues],
+ () => ({ controller, issues, canCreate }),
+ [controller, issues, canCreate],
);
const openCreateIssue = useCallback(
(defaults?: IssueCreateDefaults) => {
@@ -344,7 +350,7 @@ function IssueSurfaceContent({
title={t(($) => $.detail.empty_issues_title)}
description={t(($) => $.detail.empty_issues_hint)}
actions={
- allowCreate && <>
+ canCreate && <>
<Button size="sm" onClick={() => controller.openCreateIssue()}>
<Plus aria-hidden="true" />
{t(($) => $.detail.empty_issues_new_button)}
@@ -376,7 +382,7 @@ function IssueSurfaceContent({
childProgressMap={controller.childProgressMap}
projectMap={controller.projectMap}
projectId={controller.projectId}
- onCreateIssue={allowCreate ? openCreateIssue : undefined}
+ onCreateIssue={canCreate ? openCreateIssue : undefined}
statusPagination={controller.statusPagination}
groupBranches={controller.groupBranches}
/>
@@ -389,7 +395,7 @@ function IssueSurfaceContent({
projectMap={controller.projectMap}
projectId={controller.projectId}
onMoveIssue={controller.moveIssue}
- onCreateIssue={allowCreate ? openCreateIssue : undefined}
+ onCreateIssue={canCreate ? openCreateIssue : undefined}
statusPagination={controller.statusPagination!}
/>
)}
@@ -400,7 +406,7 @@ function IssueSurfaceContent({
search={controller.tableSearch}
onSearchChange={controller.setTableSearch}
onLoadedIssuesChange={handleTableLoadedIssuesChange}
- onCreateIssue={openCreateIssue}
+ onCreateIssue={guest ? undefined : openCreateIssue}
exportIssues={controller.exportTableIssues}
resolveExportLookups={controller.resolveTableExportLookups}
/>
@@ -418,7 +424,7 @@ function IssueSurfaceContent({
childProgressMap={controller.childProgressMap}
projectMap={controller.projectMap}
projectId={controller.projectId}
- onCreateIssue={allowCreate ? openCreateIssue : undefined}
+ onCreateIssue={canCreate ? openCreateIssue : undefined}
groupBranches={controller.groupBranches}
/>
)}
diff --git a/packages/views/layout/app-rail.test.tsx b/packages/views/layout/app-rail.test.tsx
index f77c62b982..1449d5476b 100644
--- a/packages/views/layout/app-rail.test.tsx
+++ b/packages/views/layout/app-rail.test.tsx
@@ -29,6 +29,10 @@ const state = vi.hoisted(() => ({
markAllChatsRead: vi.fn(),
}));
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("../navigation", () => ({
AppLink: ({
children,
diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsx
index 6a12bef65e..08fbc5aa7d 100644
--- a/packages/views/layout/app-rail.tsx
+++ b/packages/views/layout/app-rail.tsx
@@ -30,6 +30,7 @@ import { useMarkAllInboxRead } from "@multica/core/inbox/mutations";
import { useInboxSnoozeWake } from "@multica/core/inbox/use-snooze-wake";
import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
import { resolveRailOrder, useRailOrderStore } from "@multica/core/navigation";
+import { useIsGuest } from "@multica/core/permissions";
import {
RAIL_SPACES,
useCurrentWorkspace,
@@ -74,8 +75,9 @@ type RailBadge =
* what. A dot must be something the user can clear, so a failed autopilot run
* is shown in the Autopilots panel only.
*/
-function useRailBadges(): Partial<Record<RailSpaceId, RailBadge>> {
+function useRailBadges(guest: boolean): Partial<Record<RailSpaceId, RailBadge>> {
const wsId = useCurrentWorkspace()?.id;
+ const memberWsId = guest ? undefined : wsId;
const p = useWorkspacePaths();
const { pathname } = useNavigation();
const inboxUnread = useInboxUnreadCount(wsId);
@@ -84,7 +86,7 @@ function useRailBadges(): Partial<Record<RailSpaceId, RailBadge>> {
const { data: chatSessions = [] } = useQuery({
...chatSessionsOptions(wsId ?? ""),
- enabled: !!wsId,
+ enabled: !!memberWsId,
});
// The session the user is reading right now must not count: its row shows 0
// (auto mark-read is about to clear it) and a reply landing there would
@@ -104,7 +106,7 @@ function useRailBadges(): Partial<Record<RailSpaceId, RailBadge>> {
[chatSessions, viewedChatSessionId],
);
- const { stuck } = useTeamAgentStatus(wsId);
+ const { stuck } = useTeamAgentStatus(memberWsId);
const badges: Partial<Record<RailSpaceId, RailBadge>> = {};
if (inboxBadge && inboxUnread > 0) badges.work = { kind: "count", value: inboxUnread, tone: "brand" };
@@ -360,9 +362,11 @@ export function AppRail({
const { t } = useT("layout");
const p = useWorkspacePaths();
const shell = useAppShell();
- const badges = useRailBadges();
- const space = shell?.space ?? null;
const wsId = useCurrentWorkspace()?.id;
+ // A guest (MUL-9420) has only the Work space and cannot create issues.
+ const guest = useIsGuest(wsId);
+ const badges = useRailBadges(guest);
+ const space = shell?.space ?? null;
const workHref = useInboxReturnHref(shell?.spaceHref("work", p.issues()) ?? p.issues(), wsId);
const settingsPeek = usePeekHandlers("settings", space === "settings");
const savedOrder = useRailOrderStore((s) => s.order);
@@ -440,33 +444,35 @@ export function AppRail({
{topSlot}
<RailWorkspaces />
<div className="my-2 flex flex-col items-center gap-1">
- <NewIssueButton className={RAIL_ICON_BUTTON_CLASS} tooltipSide="right" />
+ {!guest && <NewIssueButton className={RAIL_ICON_BUTTON_CLASS} tooltipSide="right" />}
<SearchButton className={RAIL_ICON_BUTTON_CLASS} tooltipSide="right" />
</div>
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={DRAG_MODIFIERS}
- onDragStart={armClickGuard}
- onDragEnd={onDragEnd}
- onDragCancel={releaseClickGuard}
- >
- <SortableContext items={visibleOrder} strategy={verticalListSortingStrategy}>
- <ul className="flex flex-col items-center gap-0.5">
- {visibleOrder.map((id) => (
- <SortableRailItem key={id} id={id}>
- <RailSpaceLink
- space={id}
- {...items[id]}
- href={id === "work" ? workHref : (shell?.spaceHref(id, items[id].href) ?? items[id].href)}
- active={space === id}
- badge={badges[id]}
- />
- </SortableRailItem>
- ))}
- </ul>
- </SortableContext>
- </DndContext>
+ {!guest && (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ modifiers={DRAG_MODIFIERS}
+ onDragStart={armClickGuard}
+ onDragEnd={onDragEnd}
+ onDragCancel={releaseClickGuard}
+ >
+ <SortableContext items={visibleOrder} strategy={verticalListSortingStrategy}>
+ <ul className="flex flex-col items-center gap-0.5">
+ {visibleOrder.map((id) => (
+ <SortableRailItem key={id} id={id}>
+ <RailSpaceLink
+ space={id}
+ {...items[id]}
+ href={id === "work" ? workHref : (shell?.spaceHref(id, items[id].href) ?? items[id].href)}
+ active={space === id}
+ badge={badges[id]}
+ />
+ </SortableRailItem>
+ ))}
+ </ul>
+ </SortableContext>
+ </DndContext>
+ )}
<div className="mt-auto flex flex-col items-center gap-1 pt-2">
<HelpLauncher />
<TooltipHint label={t(($) => $.nav.settings)} side="right">
diff --git a/packages/views/layout/bottom-bar.test.tsx b/packages/views/layout/bottom-bar.test.tsx
index 1ebc43950d..1781fb6c78 100644
--- a/packages/views/layout/bottom-bar.test.tsx
+++ b/packages/views/layout/bottom-bar.test.tsx
@@ -17,6 +17,10 @@ const h = vi.hoisted(() => ({
team: { working: [], stuck: [], byAgent: new Map() } as TeamStatus,
}));
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("@multica/core/chat", () => ({
useChatStore: Object.assign(
(selector: (state: typeof h.chat) => unknown) => selector(h.chat),
diff --git a/packages/views/layout/bottom-bar.tsx b/packages/views/layout/bottom-bar.tsx
index f3f65e763b..06199882e3 100644
--- a/packages/views/layout/bottom-bar.tsx
+++ b/packages/views/layout/bottom-bar.tsx
@@ -3,6 +3,7 @@
import { TriangleAlert } from "@multica/ui/icons";
import { useChatStore } from "@multica/core/chat";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { TrialStatus } from "../billing/trial-status";
import { ChatBar } from "../chat/components/chat-bar";
@@ -56,6 +57,9 @@ export function AppBottomBar() {
const floatingChatEnabled = useChatStore((s) => s.floatingChatEnabled);
const { pathname } = useNavigation();
const chatPath = useWorkspacePaths().chat();
+ // Chat and team status are about agents, and the trial about billing, none
+ // of which a guest (MUL-9420) has access to.
+ const guest = useIsGuest(wsId);
if (!wsId || isMobile) return null;
// Same gates as the floating window: the Settings preference, and the Chat
@@ -72,10 +76,10 @@ export function AppBottomBar() {
className="hidden h-8 shrink-0 items-center justify-between gap-4 pr-[18px] pl-3 md:flex"
>
<div className="flex min-w-0 items-center gap-1">
- <TrialStatus wsId={wsId} />
- <TeamStatus wsId={wsId} />
+ {!guest && <TrialStatus wsId={wsId} />}
+ {!guest && <TeamStatus wsId={wsId} />}
</div>
- {showChat && <ChatBar />}
+ {!guest && showChat && <ChatBar />}
</footer>
);
}
diff --git a/packages/views/layout/dashboard-guard.tsx b/packages/views/layout/dashboard-guard.tsx
index f2533ac12d..4d7eab9a21 100644
--- a/packages/views/layout/dashboard-guard.tsx
+++ b/packages/views/layout/dashboard-guard.tsx
@@ -23,9 +23,9 @@ export function DashboardGuard({
children,
loadingFallback = null,
}: DashboardGuardProps) {
- const { user, isLoading, workspace } = useDashboardGuard();
+ const { user, isLoading, workspace, guestBlocked } = useDashboardGuard();
- if (isLoading || !workspace) return <>{loadingFallback}</>;
+ if (isLoading || !workspace || guestBlocked) return <>{loadingFallback}</>;
if (!user) return null;
return <>{children}</>;
diff --git a/packages/views/layout/global-shortcuts.chat.test.tsx b/packages/views/layout/global-shortcuts.chat.test.tsx
index c7530224e1..3e5efe9e0b 100644
--- a/packages/views/layout/global-shortcuts.chat.test.tsx
+++ b/packages/views/layout/global-shortcuts.chat.test.tsx
@@ -21,6 +21,7 @@ const h = vi.hoisted(() => ({
navigation: { pathname: "/acme/issues", push: vi.fn() },
toggleSidebar: vi.fn(),
searchToggle: vi.fn(),
+ guest: false,
}));
vi.mock("@multica/core/chat", () => ({
@@ -35,7 +36,9 @@ vi.mock("@multica/core/issues/stores", () => ({
vi.mock("@multica/core/modals", () => ({
useModalStore: { getState: () => ({ modal: null }) },
}));
+vi.mock("@multica/core/permissions", () => ({ useIsGuest: () => h.guest }));
vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-1" }),
useWorkspacePaths: () => ({
inbox: () => "/acme/inbox",
chat: () => "/acme/chat",
@@ -92,6 +95,7 @@ beforeEach(() => {
h.chat.isOpen = false;
h.chat.activeSessionId = null;
h.navigation.pathname = "/acme/issues";
+ h.guest = false;
});
afterEach(() => {
@@ -124,6 +128,16 @@ describe("chat toggle shortcut", () => {
expect(openCreateIssueWithPreference).toHaveBeenCalledTimes(1);
});
+ it("leaves C unclaimed for a guest, who cannot create issues (MUL-9420)", () => {
+ h.guest = true;
+ render(<GlobalShortcuts />);
+ const event = new KeyboardEvent("keydown", { key: "c", bubbles: true, cancelable: true });
+ document.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(openCreateIssueWithPreference).not.toHaveBeenCalled();
+ });
+
it("toggles the floating window and consumes the chord", () => {
render(<GlobalShortcuts />);
diff --git a/packages/views/layout/global-shortcuts.history.test.tsx b/packages/views/layout/global-shortcuts.history.test.tsx
index 7a07cda073..d7c4e1e145 100644
--- a/packages/views/layout/global-shortcuts.history.test.tsx
+++ b/packages/views/layout/global-shortcuts.history.test.tsx
@@ -13,7 +13,9 @@ vi.mock("@multica/ui/components/ui/sidebar", () => ({
vi.mock("@multica/core/chat", () => ({
useChatStore: { getState: () => ({ floatingChatEnabled: false }) },
}));
+vi.mock("@multica/core/permissions", () => ({ useIsGuest: () => false }));
vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "w" }),
useWorkspacePaths: () => ({
inbox: () => "/w/inbox",
chat: () => "/w/chat",
diff --git a/packages/views/layout/global-shortcuts.tsx b/packages/views/layout/global-shortcuts.tsx
index 804b291c1c..cbebb89ccd 100644
--- a/packages/views/layout/global-shortcuts.tsx
+++ b/packages/views/layout/global-shortcuts.tsx
@@ -13,7 +13,8 @@ import {
import { useChatStore } from "@multica/core/chat";
import { useSearchStore } from "@multica/core/command-bar";
import { useModalStore } from "@multica/core/modals";
-import { useWorkspacePaths } from "@multica/core/paths";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { isImeComposing } from "@multica/core/utils";
import { isFloatingChatRouteSuppressed } from "../chat/floating-chat-visibility";
import { useAppShell } from "./app-shell-context";
@@ -52,6 +53,8 @@ export function GlobalShortcuts() {
const toggleNav = useAppShell()?.toggleNav ?? toggleSidebar;
const navigation = useNavigation();
const workspacePaths = useWorkspacePaths();
+ // A guest (MUL-9420) cannot create issues, so its `C` stays unclaimed.
+ const guest = useIsGuest(useCurrentWorkspace()?.id);
// Subscribe so changing a binding in Settings immediately refreshes the
// listener closure; getShortcut remains useful to non-React call sites.
@@ -97,6 +100,7 @@ export function GlobalShortcuts() {
if ((candidate === "toggleChat" || candidate === "newChat") && !canUseFloatingChat()) {
return false;
}
+ if (candidate === "createIssue" && guest) return false;
return shortcutMatchesEvent(getShortcut(candidate), event);
});
if (!actionId) return;
@@ -145,7 +149,7 @@ export function GlobalShortcuts() {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [navigation, overrides, toggleNav, workspacePaths]);
+ }, [guest, navigation, overrides, toggleNav, workspacePaths]);
return null;
}
diff --git a/packages/views/layout/panels/guest-work-panel.tsx b/packages/views/layout/panels/guest-work-panel.tsx
new file mode 100644
index 0000000000..f55cc24357
--- /dev/null
+++ b/packages/views/layout/panels/guest-work-panel.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { Eye } from "@multica/ui/icons";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { useInboxUnreadCount } from "@multica/core/inbox/queries";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { Project } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { useT } from "../../i18n";
+import { PanelBody, PanelCount, PanelHeader, PanelLink, PanelList, PanelSection, isPathWithin } from "../panel-nav";
+import { routeIconForPath } from "../route-icon-components";
+
+const EMPTY_PROJECTS: Project[] = [];
+
+/**
+ * The Work panel for a guest (MUL-9420): its Inbox, the issues it takes part
+ * in, and the projects shared with it. Everything else in the workspace is
+ * out of a guest's reach, so nothing else is listed.
+ */
+export function GuestWorkPanel() {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const { pathname } = useNavigation();
+ const workspace = useCurrentWorkspace();
+ const wsId = workspace?.id;
+ const unread = useInboxUnreadCount(wsId);
+ const { data: projects = EMPTY_PROJECTS } = useQuery({
+ ...projectListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const shared = projects.filter((project) => !project.archived_at);
+ const InboxIcon = routeIconForPath(p.inbox());
+ const InvolvedIcon = routeIconForPath(p.myIssues());
+
+ return (
+ <>
+ <PanelHeader title={workspace?.name ?? t(($) => $.spaces.work)}>
+ <TooltipHint label={t(($) => $.panels.work.guest_badge_hint)} side="bottom">
+ <Badge variant="secondary" className="shrink-0 gap-1">
+ <Eye className="size-3" aria-hidden="true" />
+ {t(($) => $.panels.work.guest_badge)}
+ </Badge>
+ </TooltipHint>
+ </PanelHeader>
+ <PanelBody>
+ <PanelList>
+ <PanelLink
+ href={p.inbox()}
+ icon={<InboxIcon />}
+ label={t(($) => $.nav.inbox)}
+ active={pathname === p.inbox()}
+ trailing={<PanelCount value={unread} />}
+ />
+ <PanelLink
+ href={p.myIssues()}
+ icon={<InvolvedIcon />}
+ label={t(($) => $.panels.work.involved)}
+ active={isPathWithin(pathname, p.myIssues())}
+ />
+ </PanelList>
+ <PanelSection label={t(($) => $.panels.work.shared_projects)}>
+ <PanelList>
+ {shared.map((project) => (
+ <PanelLink
+ key={project.id}
+ href={p.projectDetail(project.id)}
+ icon={<ProjectIcon project={project} size="md" />}
+ label={project.title}
+ active={isPathWithin(pathname, p.projectDetail(project.id))}
+ trailing={<PanelCount value={project.issue_count - project.done_count} />}
+ />
+ ))}
+ </PanelList>
+ </PanelSection>
+ </PanelBody>
+ </>
+ );
+}
diff --git a/packages/views/layout/route-data-prefetch.tsx b/packages/views/layout/route-data-prefetch.tsx
index 682addd40b..8097f0bcbc 100644
--- a/packages/views/layout/route-data-prefetch.tsx
+++ b/packages/views/layout/route-data-prefetch.tsx
@@ -11,6 +11,7 @@ import { autopilotListOptions } from "@multica/core/autopilots/queries";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { inboxListOptions } from "@multica/core/inbox/queries";
import { useAuthStore } from "@multica/core/auth";
+import { useIsGuest } from "@multica/core/permissions";
import { paths, useCurrentWorkspace, useWorkspaceSlug } from "@multica/core/paths";
import { pinListOptions } from "@multica/core/pins/queries";
import { projectListOptions } from "@multica/core/projects/queries";
@@ -72,6 +73,9 @@ const ROUTES = {
type RouteKey = keyof typeof ROUTES;
+// A guest (MUL-9420) only reaches these pages.
+const GUEST_ROUTES: RouteKey[] = ["projects", "inbox"];
+
// Small, workspace-scoped lists worth fetching before anyone asks, so the
// first visit to each is already warm. Unobserved queries are collected after
// their gcTime; hover/focus prefetch covers visits after that.
@@ -91,10 +95,12 @@ const WARM_ON_IDLE: RouteKey[] = [
export function RouteDataPrefetch({
wsId,
userId,
+ guest = false,
children,
}: {
wsId: string | undefined;
userId: string | null;
+ guest?: boolean;
children: ReactNode;
}) {
const qc = useQueryClient();
@@ -104,10 +110,9 @@ export function RouteDataPrefetch({
const routeByHref = useMemo(() => {
if (!slug) return new Map<string, WarmRoute>();
const p = paths.workspace(slug);
- return new Map<string, WarmRoute>(
- (Object.keys(ROUTES) as RouteKey[]).map((key) => [p[key](), ROUTES[key]]),
- );
- }, [slug]);
+ const keys = guest ? GUEST_ROUTES : (Object.keys(ROUTES) as RouteKey[]);
+ return new Map<string, WarmRoute>(keys.map((key) => [p[key](), ROUTES[key]]));
+ }, [slug, guest]);
const prefetch = useCallback(
(href: string) => {
@@ -121,7 +126,7 @@ export function RouteDataPrefetch({
useEffect(() => {
if (!wsId) return;
const warm = () => {
- for (const key of WARM_ON_IDLE) ROUTES[key](qc, wsId, userId);
+ for (const key of guest ? GUEST_ROUTES : WARM_ON_IDLE) ROUTES[key](qc, wsId, userId);
};
if (typeof window.requestIdleCallback === "function") {
const id = window.requestIdleCallback(warm, { timeout: 3000 });
@@ -129,7 +134,7 @@ export function RouteDataPrefetch({
}
const timer = window.setTimeout(warm, 1500);
return () => window.clearTimeout(timer);
- }, [qc, wsId, userId]);
+ }, [qc, wsId, userId, guest]);
return (
<RouteDataPrefetchProvider value={prefetch}>
@@ -142,8 +147,9 @@ export function RouteDataPrefetch({
export function ShellRouteDataPrefetch({ children }: { children: ReactNode }) {
const wsId = useCurrentWorkspace()?.id;
const userId = useAuthStore((s) => s.user?.id ?? null);
+ const guest = useIsGuest(wsId);
return (
- <RouteDataPrefetch wsId={wsId} userId={userId}>
+ <RouteDataPrefetch wsId={wsId} userId={userId} guest={guest}>
{children}
</RouteDataPrefetch>
);
diff --git a/packages/views/layout/space-panel.test.tsx b/packages/views/layout/space-panel.test.tsx
index be3a875dd1..b92e621003 100644
--- a/packages/views/layout/space-panel.test.tsx
+++ b/packages/views/layout/space-panel.test.tsx
@@ -7,6 +7,14 @@ import { SpacePanel } from "./space-panel";
const navigation = vi.hoisted(() => ({ pathname: "/acme/issues" }));
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useCurrentWorkspace: () => null,
+}));
+vi.mock("@multica/core/permissions", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/permissions")>()),
+ useIsGuest: () => false,
+}));
vi.mock("../navigation", () => ({
useNavigation: () => ({ pathname: navigation.pathname }),
}));
diff --git a/packages/views/layout/space-panel.tsx b/packages/views/layout/space-panel.tsx
index d1ac2f008a..0f3fec57e3 100644
--- a/packages/views/layout/space-panel.tsx
+++ b/packages/views/layout/space-panel.tsx
@@ -2,19 +2,27 @@
import { DocTree } from "../docs/components/doc-tree";
import { useEffect, useRef } from "react";
-import type { AppSpaceId } from "@multica/core/paths";
+import { useCurrentWorkspace, type AppSpaceId } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { cn } from "@multica/ui/lib/utils";
import { useSidebar } from "@multica/ui/components/ui/sidebar";
import { useAppShell } from "./app-shell-context";
import { PanelResizeHandle } from "./panel-resize-handle";
import { AutopilotsPanel } from "./panels/autopilots-panel";
+import { GuestWorkPanel } from "./panels/guest-work-panel";
import { ChatPeek } from "./panels/list-space-peeks";
import { LIST_COLUMN_WIDTH_CLASS, NAV_COLUMN_MOTION_CLASS, NAV_PEEK_CLASS } from "./rail-styles";
import { TeamPanel } from "./panels/team-panel";
import { KeptRowsRelease, WorkPanel } from "./panels/work-panel";
+/** A guest (MUL-9420) sees its own Work panel: only what is shared with it. */
+function WorkSpacePanel() {
+ const guest = useIsGuest(useCurrentWorkspace()?.id);
+ return guest ? <GuestWorkPanel /> : <WorkPanel />;
+}
+
const PANELS: Partial<Record<AppSpaceId, () => React.ReactNode>> = {
- work: WorkPanel,
+ work: WorkSpacePanel,
docs: DocTree,
team: TeamPanel,
autopilots: AutopilotsPanel,
diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.ts
index 0c14688a2f..98c5235e18 100644
--- a/packages/views/layout/use-dashboard-guard.ts
+++ b/packages/views/layout/use-dashboard-guard.ts
@@ -10,6 +10,7 @@ import {
useHasOnboarded,
} from "@multica/core/paths";
import { useWorkspaceList } from "@multica/core/workspace";
+import { useIsGuest } from "@multica/core/permissions";
import { useRecentIssuesStore } from "@multica/core/issues/stores";
import { useRecentVisitsStore } from "@multica/core/command-bar";
import { useNavigation } from "../navigation";
@@ -39,6 +40,10 @@ import { useNavigation } from "../navigation";
* from "slug not found". Otherwise users could see a transient redirect
* before their workspace list arrives.
*/
+// The workspace sections a guest (MUL-9420) may open; every other section is
+// about agents or workspace administration, which the server refuses it.
+const GUEST_SECTIONS = new Set(["inbox", "my-issues", "issues", "projects", "settings"]);
+
export function useDashboardGuard() {
const { pathname, replace } = useNavigation();
const user = useAuthStore((s) => s.user);
@@ -61,6 +66,13 @@ export function useDashboardGuard() {
}
}, [user, isLoading, workspaceListReady, workspace, workspaces, hasOnboarded, replace]);
+ const guest = useIsGuest(workspace?.id);
+ const section = pathname.split("/")[2] ?? "";
+ const guestBlocked = guest && !!workspace && !GUEST_SECTIONS.has(section);
+ useEffect(() => {
+ if (guestBlocked && workspace) replace(paths.workspace(workspace.slug).inbox());
+ }, [guestBlocked, workspace, replace]);
+
useEffect(() => {
useNavigationStore.getState().onPathChange(pathname);
}, [pathname]);
@@ -75,5 +87,5 @@ export function useDashboardGuard() {
useRecentVisitsStore.getState().pruneWorkspaces(activeWsIds);
}, [workspaceListReady, workspaces]);
- return { user, isLoading, workspace };
+ return { user, isLoading, workspace, guestBlocked };
}
diff --git a/packages/views/layout/workspace-presence-prefetch.tsx b/packages/views/layout/workspace-presence-prefetch.tsx
index 0de8899d71..48708ae120 100644
--- a/packages/views/layout/workspace-presence-prefetch.tsx
+++ b/packages/views/layout/workspace-presence-prefetch.tsx
@@ -2,6 +2,7 @@
import { useWorkspaceId } from "@multica/core";
import { useWorkspacePresencePrefetch } from "@multica/core/agents";
+import { useIsGuest } from "@multica/core/permissions";
// Mount once inside any subtree that's already gated on "workspace resolved"
// (DashboardLayout on web, WorkspaceRouteLayout on desktop). useWorkspaceId
@@ -9,6 +10,11 @@ import { useWorkspacePresencePrefetch } from "@multica/core/agents";
// layouts guarantees this component never sees that state.
export function WorkspacePresencePrefetch() {
const wsId = useWorkspaceId();
+ // Agent presence is not shown to guests, and the server refuses it.
+ return useIsGuest(wsId) ? null : <PresencePrefetch wsId={wsId} />;
+}
+
+function PresencePrefetch({ wsId }: { wsId: string }) {
useWorkspacePresencePrefetch(wsId);
return null;
}
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.json
index 0c68b3cc0a..461b051665 100644
--- a/packages/views/locales/en/billing.json
+++ b/packages/views/locales/en/billing.json
@@ -314,6 +314,10 @@
"private_projects": {
"name": "Private projects",
"after": "Stay private after the trial. Their access lists become read-only."
+ },
+ "guests": {
+ "name": "Guests",
+ "after": "Existing guests keep their access after the trial. New guests need Pro or Business."
}
}
}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index c1639bcbb8..7183315639 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -610,7 +610,8 @@
"project_directory_path_copied_with_branch": "Project directory path copied — work is on {{branch}}",
"workdir_path_copy_failed": "Failed to copy workdir path",
"workdir_path_unavailable": "No local workdir yet — issue has not been run by a local agent",
- "pull_requests_empty_title": "No linked pull requests."
+ "pull_requests_empty_title": "No linked pull requests.",
+ "guest_readonly_note": "Guests can view and comment, but cannot change issue properties."
},
"timeline": {
"loading": "Loading...",
@@ -789,7 +790,9 @@
"restart_failed": "Couldn't stop the current run. Your message wasn't sent.",
"reply_action": "Reply",
"actions_label": "Comment actions",
- "create_issue_from_selection": "Create sub-issue from selection"
+ "create_issue_from_selection": "Create sub-issue from selection",
+ "guest_placeholder": "Reply… you can @ members",
+ "guest_hint": "Guests cannot @ agents or assign issues to them"
},
"reply": {
"recipients_changed": "Reply target changed. Review the recipients before sending again.",
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index e768d0d645..4901074b0e 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -192,7 +192,11 @@
"pinned_settings": "Pinned display",
"views_settings": "Views display",
"views_builtin": "Built-in views",
- "views_show_count": "Counts"
+ "views_show_count": "Counts",
+ "guest_badge": "Guest",
+ "guest_badge_hint": "You can view and comment on the projects shared with you.",
+ "involved": "Involved",
+ "shared_projects": "Shared with you"
},
"team": {
"new_agent": "New agent",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index b75b782d2c..828667008b 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1611,6 +1611,10 @@
"member": {
"label": "Member",
"description": "Create and work on issues"
+ },
+ "guest": {
+ "label": "Guest",
+ "description": "Views and comments on the projects shared with them. Can't run agents."
}
},
"share_links_create_title": "Create share link",
@@ -1660,7 +1664,32 @@
"toast_invitation_pending": "An invitation to {{email}} is already pending.",
"toast_invite_check_unavailable": "Could not check existing members and invitations. Try again in a moment.",
"member_limit_full_description_billing": "The workspace's subscription needs attention. Restore it in Billing to add members, or remove a member first.",
- "open_billing": "Open Billing"
+ "open_billing": "Open Billing",
+ "guest_free_tag": "Free · no seat",
+ "guest_projects_label": "Projects they can access",
+ "guest_projects_add": "Add project…",
+ "guest_projects_remove": "Remove {{project}}",
+ "guest_projects_hint": "Guests can't see other projects, agents, autopilots or settings.",
+ "invite_guest_button": "Invite guest",
+ "all_label": "All",
+ "guests_label": "Guests",
+ "guest_count": "Guests: {{count}}",
+ "list_separator": ", ",
+ "takes_seat": "Takes 1 seat",
+ "frees_seat": "Frees a seat",
+ "make_member": "Make member",
+ "make_member_title": "Make {{name}} a member?",
+ "make_member_description": "{{name}} will see the whole workspace and can run agents. This takes 1 seat.",
+ "make_member_seat_description": "{{name}} will see the whole workspace and can run agents. All purchased seats are in use, so this buys 1 more.",
+ "purchase_seat_and_make_member": "Buy seat and make member",
+ "making_member": "Making member…",
+ "make_guest_title": "Make {{name}} a guest",
+ "make_guest_description": "{{name}} will only see the projects below and frees a seat. Their agents, autopilots and runtime access are taken back.",
+ "make_guest_button": "Make guest",
+ "manage_projects": "Manage accessible projects",
+ "manage_projects_title": "Projects {{name}} can access",
+ "save_projects": "Save",
+ "toast_projects_updated": "Projects updated"
},
"integrations": {
"status_connected": "Connected",
diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.json
index febf6dfd24..c36d8785c7 100644
--- a/packages/views/locales/es/billing.json
+++ b/packages/views/locales/es/billing.json
@@ -314,6 +314,10 @@
"private_projects": {
"name": "Proyectos privados",
"after": "Siguen siendo privados después de la prueba. Sus listas de acceso pasan a solo lectura."
+ },
+ "guests": {
+ "name": "Invitados",
+ "after": "Los invitados actuales conservan su acceso después de la prueba. Para invitar a nuevos invitados necesitas Pro o Business."
}
}
}
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index 572fe89ad0..39160172f5 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -593,7 +593,8 @@
"thread_nav_hide_replies": "Ocultar respuestas",
"load_failed": "No se pudo cargar la tarea.",
"load_retry": "Reintentar",
- "not_found_title": "Tarea no encontrada"
+ "not_found_title": "Tarea no encontrada",
+ "guest_readonly_note": "Los invitados pueden ver y comentar, pero no cambiar las propiedades de la tarea."
},
"timeline": {
"loading": "Cargando...",
@@ -772,7 +773,9 @@
"restart_failed": "No se ha podido detener la ejecución actual. Tu mensaje no se envió.",
"reply_action": "Responder",
"actions_label": "Acciones del comentario",
- "create_issue_from_selection": "Crear subtarea a partir de la selección"
+ "create_issue_from_selection": "Crear subtarea a partir de la selección",
+ "guest_placeholder": "Responder… puedes mencionar a miembros con @",
+ "guest_hint": "Los invitados no pueden mencionar agentes ni asignarles tareas"
},
"reply": {
"recipients_changed": "El destino de la respuesta ha cambiado. Revisa los destinatarios antes de volver a enviar.",
diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.json
index 115edd33bf..41963474ed 100644
--- a/packages/views/locales/es/layout.json
+++ b/packages/views/locales/es/layout.json
@@ -192,7 +192,11 @@
"pinned_settings": "Visualización de fijados",
"views_settings": "Visualización de vistas",
"views_builtin": "Vistas integradas",
- "views_show_count": "Recuentos"
+ "views_show_count": "Recuentos",
+ "guest_badge": "Invitado",
+ "guest_badge_hint": "Puedes ver y comentar los proyectos compartidos contigo.",
+ "involved": "Mis tareas",
+ "shared_projects": "Compartidos contigo"
},
"team": {
"new_agent": "Nuevo agente",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index bb52028355..542eeb0c7b 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -1611,6 +1611,10 @@
"member": {
"label": "Miembro",
"description": "Crea tareas y trabaja en ellas"
+ },
+ "guest": {
+ "label": "Invitado",
+ "description": "Ve y comenta los proyectos compartidos con él. No puede ejecutar agentes."
}
},
"share_links_create_title": "Crear enlace de invitación",
@@ -1660,7 +1664,32 @@
"toast_invitation_pending": "Ya hay una invitación pendiente para {{email}}.",
"toast_invite_check_unavailable": "No se pudieron comprobar los miembros y las invitaciones actuales. Inténtalo de nuevo en un momento.",
"member_limit_full_description_billing": "La suscripción del espacio de trabajo necesita atención. Restablécela en Facturación para añadir miembros, o elimina antes a un miembro.",
- "open_billing": "Abrir Facturación"
+ "open_billing": "Abrir Facturación",
+ "guest_free_tag": "Gratis · sin asiento",
+ "guest_projects_label": "Proyectos a los que puede acceder",
+ "guest_projects_add": "Añadir proyecto…",
+ "guest_projects_remove": "Quitar {{project}}",
+ "guest_projects_hint": "Los invitados no ven otros proyectos, agentes, automatizaciones ni ajustes.",
+ "invite_guest_button": "Invitar invitado",
+ "all_label": "Todos",
+ "guests_label": "Invitados",
+ "guest_count": "Invitados: {{count}}",
+ "list_separator": ", ",
+ "takes_seat": "Ocupa 1 asiento",
+ "frees_seat": "Libera un asiento",
+ "make_member": "Convertir en miembro",
+ "make_member_title": "¿Convertir a {{name}} en miembro?",
+ "make_member_description": "{{name}} verá todo el espacio de trabajo y podrá ejecutar agentes. Ocupa 1 asiento.",
+ "make_member_seat_description": "{{name}} verá todo el espacio de trabajo y podrá ejecutar agentes. Todos los asientos están ocupados, así que se compra 1 más.",
+ "purchase_seat_and_make_member": "Comprar asiento y convertir",
+ "making_member": "Convirtiendo…",
+ "make_guest_title": "Convertir a {{name}} en invitado",
+ "make_guest_description": "{{name}} solo verá los proyectos de abajo y liberará un asiento. Se retiran sus agentes, automatizaciones y acceso a runtimes.",
+ "make_guest_button": "Convertir en invitado",
+ "manage_projects": "Gestionar proyectos accesibles",
+ "manage_projects_title": "Proyectos a los que {{name}} puede acceder",
+ "save_projects": "Guardar",
+ "toast_projects_updated": "Proyectos actualizados"
},
"integrations": {
"status_connected": "Conectado",
diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.json
index 7fc571285d..da0c94c50e 100644
--- a/packages/views/locales/fr/billing.json
+++ b/packages/views/locales/fr/billing.json
@@ -314,6 +314,10 @@
"private_projects": {
"name": "Projets privés",
"after": "Restent privés après l'essai. Leurs listes d'accès passent en lecture seule."
+ },
+ "guests": {
+ "name": "Invités",
+ "after": "Les invités existants gardent leur accès après l'essai. Inviter de nouveaux invités nécessite Pro ou Business."
}
}
}
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index ceb4bf8782..a404c2828a 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -610,7 +610,8 @@
"project_directory_path_copied_with_branch": "Chemin du répertoire du projet copié — le travail se trouve sur {{branch}}",
"workdir_path_copy_failed": "Échec de la copie du chemin du répertoire de travail",
"workdir_path_unavailable": "Aucun répertoire de travail local — cette tâche n'a pas encore été traitée par un agent local",
- "pull_requests_empty_title": "Aucune pull request associée."
+ "pull_requests_empty_title": "Aucune pull request associée.",
+ "guest_readonly_note": "Les invités peuvent consulter et commenter, mais pas modifier les propriétés de la tâche."
},
"timeline": {
"loading": "Chargement...",
@@ -789,7 +790,9 @@
"restart_failed": "Impossible d'arrêter l'exécution en cours. Votre message n'a pas été envoyé.",
"reply_action": "Répondre",
"actions_label": "Actions du commentaire",
- "create_issue_from_selection": "Créer une sous-tâche à partir de la sélection"
+ "create_issue_from_selection": "Créer une sous-tâche à partir de la sélection",
+ "guest_placeholder": "Répondre… vous pouvez @ mentionner des membres",
+ "guest_hint": "Les invités ne peuvent pas @ mentionner d'agents ni leur assigner de tâches"
},
"reply": {
"recipients_changed": "La cible de la réponse a changé. Vérifiez les destinataires avant de réessayer.",
diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.json
index fb218c5b13..99cf596fb9 100644
--- a/packages/views/locales/fr/layout.json
+++ b/packages/views/locales/fr/layout.json
@@ -192,7 +192,11 @@
"pinned_settings": "Affichage des épingles",
"views_settings": "Affichage des vues",
"views_builtin": "Vues intégrées",
- "views_show_count": "Compteurs"
+ "views_show_count": "Compteurs",
+ "guest_badge": "Invité",
+ "guest_badge_hint": "Vous pouvez consulter et commenter les projets partagés avec vous.",
+ "involved": "Mes tâches",
+ "shared_projects": "Partagés avec vous"
},
"team": {
"new_agent": "Nouvel agent",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 805d93b5d7..4a6aeb4fd0 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -1611,6 +1611,10 @@
"member": {
"label": "Membre",
"description": "Créer des tâches et y travailler"
+ },
+ "guest": {
+ "label": "Invité",
+ "description": "Consulte et commente les projets partagés avec lui. Ne peut pas lancer d'agents."
}
},
"share_links_create_title": "Créer un lien de partage",
@@ -1660,7 +1664,32 @@
"toast_invitation_pending": "Une invitation pour {{email}} est déjà en attente.",
"toast_invite_check_unavailable": "Impossible de vérifier les membres et invitations existants. Réessayez dans un instant.",
"member_limit_full_description_billing": "L'abonnement de l'espace de travail demande votre attention. Rétablissez-le dans Facturation pour ajouter des membres, ou retirez d'abord un membre.",
- "open_billing": "Ouvrir Facturation"
+ "open_billing": "Ouvrir Facturation",
+ "guest_free_tag": "Gratuit · sans siège",
+ "guest_projects_label": "Projets accessibles",
+ "guest_projects_add": "Ajouter un projet…",
+ "guest_projects_remove": "Retirer {{project}}",
+ "guest_projects_hint": "Les invités ne voient ni les autres projets, ni les agents, automatisations ou réglages.",
+ "invite_guest_button": "Inviter l'invité",
+ "all_label": "Tous",
+ "guests_label": "Invités",
+ "guest_count": "Invités : {{count}}",
+ "list_separator": ", ",
+ "takes_seat": "Occupe 1 siège",
+ "frees_seat": "Libère un siège",
+ "make_member": "Passer en membre",
+ "make_member_title": "Passer {{name}} en membre ?",
+ "make_member_description": "{{name}} verra tout l'espace de travail et pourra lancer des agents. Cela occupe 1 siège.",
+ "make_member_seat_description": "{{name}} verra tout l'espace de travail et pourra lancer des agents. Tous les sièges achetés sont occupés : un siège de plus sera acheté.",
+ "purchase_seat_and_make_member": "Acheter un siège et passer en membre",
+ "making_member": "Passage en membre…",
+ "make_guest_title": "Passer {{name}} en invité",
+ "make_guest_description": "{{name}} ne verra que les projets ci-dessous et libère un siège. Ses agents, automatisations et accès aux runtimes sont retirés.",
+ "make_guest_button": "Passer en invité",
+ "manage_projects": "Gérer les projets accessibles",
+ "manage_projects_title": "Projets accessibles à {{name}}",
+ "save_projects": "Enregistrer",
+ "toast_projects_updated": "Projets mis à jour"
},
"integrations": {
"status_connected": "Connecté",
diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.json
index 390789baca..68217fe6b3 100644
--- a/packages/views/locales/ja/billing.json
+++ b/packages/views/locales/ja/billing.json
@@ -302,6 +302,10 @@
"private_projects": {
"name": "プライベートプロジェクト",
"after": "終了後も非公開のまま。アクセスリストは読み取り専用になります。"
+ },
+ "guests": {
+ "name": "ゲスト",
+ "after": "終了後も既存のゲストはアクセスを保持します。新しいゲストの招待には Pro または Business が必要です。"
}
}
}
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index a835de7a3e..e8884d4b03 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -600,7 +600,8 @@
"project_directory_path_copied_with_branch": "プロジェクトディレクトリのパスをコピーしました — 作業は {{branch}} ブランチにあります",
"workdir_path_copy_failed": "作業ディレクトリのパスをコピーできませんでした",
"workdir_path_unavailable": "まだローカルの作業ディレクトリがありません。ローカルエージェントがこのタスクを実行していません",
- "pull_requests_empty_title": "関連する PR はありません。"
+ "pull_requests_empty_title": "関連する PR はありません。",
+ "guest_readonly_note": "ゲストは閲覧とコメントのみ可能で、タスクのプロパティは変更できません。"
},
"timeline": {
"loading": "読み込み中...",
@@ -764,7 +765,9 @@
"restart_failed": "現在の実行を停止できませんでした。メッセージは送信されていません。",
"reply_action": "返信",
"actions_label": "コメントの操作",
- "create_issue_from_selection": "選択内容からサブタスクを作成"
+ "create_issue_from_selection": "選択内容からサブタスクを作成",
+ "guest_placeholder": "返信… メンバーを @ できます",
+ "guest_hint": "ゲストはエージェントを @ したり、タスクを割り当てたりできません"
},
"reply": {
"recipients_changed": "返信先が変更されました。送信先を確認してから、もう一度送信してください。",
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index 875e491650..9923f6dce1 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -188,7 +188,11 @@
"pinned_settings": "ピン留めの表示",
"views_settings": "ビューの表示",
"views_builtin": "組み込みビュー",
- "views_show_count": "件数"
+ "views_show_count": "件数",
+ "guest_badge": "ゲスト",
+ "guest_badge_hint": "共有されたプロジェクトを閲覧・コメントできます。",
+ "involved": "関わっているタスク",
+ "shared_projects": "共有されたプロジェクト"
},
"team": {
"new_agent": "新規エージェント",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 9fc93254a1..572b12abac 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1596,6 +1596,10 @@
"member": {
"label": "メンバー",
"description": "タスクの作成と作業"
+ },
+ "guest": {
+ "label": "ゲスト",
+ "description": "共有されたプロジェクトの閲覧とコメントのみ。エージェントは実行できません。"
}
},
"share_links_create_title": "共有リンクを作成",
@@ -1645,7 +1649,32 @@
"toast_invitation_pending": "{{email}} への招待はすでに保留中です。",
"toast_invite_check_unavailable": "既存のメンバーと招待を確認できませんでした。しばらくしてからもう一度お試しください。",
"member_limit_full_description_billing": "ワークスペースのサブスクリプションに対応が必要です。請求とプランで復旧するとメンバーを追加できます。先にメンバーを削除することもできます。",
- "open_billing": "請求とプランを開く"
+ "open_billing": "請求とプランを開く",
+ "guest_free_tag": "無料・席を使わない",
+ "guest_projects_label": "アクセスできるプロジェクト",
+ "guest_projects_add": "プロジェクトを追加…",
+ "guest_projects_remove": "{{project}} を外す",
+ "guest_projects_hint": "ゲストは他のプロジェクト、エージェント、オートパイロット、設定を見られません。",
+ "invite_guest_button": "ゲストを招待",
+ "all_label": "すべて",
+ "guests_label": "ゲスト",
+ "guest_count": "ゲスト {{count}} 人",
+ "list_separator": "、",
+ "takes_seat": "1 席を使用",
+ "frees_seat": "席が空く",
+ "make_member": "メンバーにする",
+ "make_member_title": "{{name}} をメンバーにしますか?",
+ "make_member_description": "{{name}} はワークスペース全体を見られ、エージェントを実行できます。1 席を使用します。",
+ "make_member_seat_description": "{{name}} はワークスペース全体を見られ、エージェントを実行できます。購入済みの席がすべて使用中のため、1 席を追加購入します。",
+ "purchase_seat_and_make_member": "席を購入してメンバーにする",
+ "making_member": "メンバーにしています…",
+ "make_guest_title": "{{name}} をゲストにする",
+ "make_guest_description": "{{name}} は下のプロジェクトだけを見られ、席が空きます。エージェント、オートパイロット、ランタイムへのアクセスは回収されます。",
+ "make_guest_button": "ゲストにする",
+ "manage_projects": "アクセスできるプロジェクトを管理",
+ "manage_projects_title": "{{name}} がアクセスできるプロジェクト",
+ "save_projects": "保存",
+ "toast_projects_updated": "プロジェクトを更新しました"
},
"integrations": {
"status_connected": "接続済み",
diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.json
index 9ce5e39c6a..5df1be8b6b 100644
--- a/packages/views/locales/ko/billing.json
+++ b/packages/views/locales/ko/billing.json
@@ -302,6 +302,10 @@
"private_projects": {
"name": "비공개 프로젝트",
"after": "체험 후에도 비공개로 유지되며, 접근 목록은 읽기 전용이 됩니다."
+ },
+ "guests": {
+ "name": "게스트",
+ "after": "체험 후에도 기존 게스트는 접근 권한을 유지합니다. 새 게스트를 초대하려면 Pro 또는 Business가 필요합니다."
}
}
}
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 4907025097..2360b0fda3 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -600,7 +600,8 @@
"project_directory_path_copied_with_branch": "프로젝트 디렉터리 경로를 복사했습니다 — 작업은 {{branch}} 브랜치에 있습니다",
"workdir_path_copy_failed": "작업 디렉터리 경로를 복사하지 못했습니다",
"workdir_path_unavailable": "아직 로컬 작업 디렉터리가 없습니다. 로컬 에이전트가 이 태스크를 실행하지 않았습니다",
- "pull_requests_empty_title": "연결된 PR이 없습니다."
+ "pull_requests_empty_title": "연결된 PR이 없습니다.",
+ "guest_readonly_note": "게스트는 보고 댓글을 남길 수 있지만 작업 속성은 바꿀 수 없습니다."
},
"timeline": {
"loading": "불러오는 중...",
@@ -764,7 +765,9 @@
"restart_failed": "현재 실행을 중지하지 못했습니다. 메시지는 보내지 않았습니다.",
"reply_action": "답글 달기",
"actions_label": "댓글 작업",
- "create_issue_from_selection": "선택한 내용으로 하위 태스크 만들기"
+ "create_issue_from_selection": "선택한 내용으로 하위 태스크 만들기",
+ "guest_placeholder": "답글… 멤버를 @ 할 수 있습니다",
+ "guest_hint": "게스트는 에이전트를 @ 하거나 작업을 배정할 수 없습니다"
},
"reply": {
"recipients_changed": "답글 대상이 변경되었습니다. 받는 사람을 확인한 뒤 다시 보내 주세요.",
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index 6e9563de59..d503237b9e 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -188,7 +188,11 @@
"pinned_settings": "고정 항목 표시",
"views_settings": "보기 표시",
"views_builtin": "기본 보기",
- "views_show_count": "개수"
+ "views_show_count": "개수",
+ "guest_badge": "게스트",
+ "guest_badge_hint": "공유된 프로젝트를 보고 댓글을 남길 수 있습니다.",
+ "involved": "참여 중",
+ "shared_projects": "공유된 프로젝트"
},
"team": {
"new_agent": "새 에이전트",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 967311f987..8ae1bb37c1 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1339,6 +1339,10 @@
"member": {
"label": "멤버",
"description": "태스크 생성 및 작업"
+ },
+ "guest": {
+ "label": "게스트",
+ "description": "공유된 프로젝트만 보고 댓글을 남길 수 있습니다. 에이전트는 실행할 수 없습니다."
}
},
"share_links_create_title": "공유 링크 만들기",
@@ -1388,7 +1392,32 @@
"toast_invitation_pending": "{{email}}에게 보낸 초대가 이미 대기 중입니다.",
"toast_invite_check_unavailable": "기존 멤버와 초대를 확인하지 못했습니다. 잠시 후 다시 시도하세요.",
"member_limit_full_description_billing": "워크스페이스 구독에 조치가 필요합니다. 결제 및 요금제에서 구독을 복구하면 멤버를 추가할 수 있습니다. 먼저 멤버를 제거할 수도 있습니다.",
- "open_billing": "결제 및 요금제 열기"
+ "open_billing": "결제 및 요금제 열기",
+ "guest_free_tag": "무료 · 좌석 없음",
+ "guest_projects_label": "접근할 수 있는 프로젝트",
+ "guest_projects_add": "프로젝트 추가…",
+ "guest_projects_remove": "{{project}} 제거",
+ "guest_projects_hint": "게스트는 다른 프로젝트, 에이전트, 자동화, 설정을 볼 수 없습니다.",
+ "invite_guest_button": "게스트 초대",
+ "all_label": "전체",
+ "guests_label": "게스트",
+ "guest_count": "게스트 {{count}}명",
+ "list_separator": ", ",
+ "takes_seat": "좌석 1개 사용",
+ "frees_seat": "좌석 반환",
+ "make_member": "멤버로 전환",
+ "make_member_title": "{{name}} 님을 멤버로 전환할까요?",
+ "make_member_description": "{{name}} 님이 워크스페이스 전체를 보고 에이전트를 실행할 수 있습니다. 좌석 1개를 사용합니다.",
+ "make_member_seat_description": "{{name}} 님이 워크스페이스 전체를 보고 에이전트를 실행할 수 있습니다. 구매한 좌석을 모두 사용 중이라 1개를 추가 구매합니다.",
+ "purchase_seat_and_make_member": "좌석 구매 후 멤버로 전환",
+ "making_member": "멤버로 전환 중…",
+ "make_guest_title": "{{name}} 님을 게스트로 전환",
+ "make_guest_description": "{{name}} 님은 아래 프로젝트만 볼 수 있고 좌석이 반환됩니다. 에이전트, 자동화, 런타임 접근은 회수됩니다.",
+ "make_guest_button": "게스트로 전환",
+ "manage_projects": "접근 가능한 프로젝트 관리",
+ "manage_projects_title": "{{name}} 님이 접근할 수 있는 프로젝트",
+ "save_projects": "저장",
+ "toast_projects_updated": "프로젝트를 업데이트했습니다"
},
"lark": {
"section_title": "Lark",
diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.json
index 44bde6c878..e0a234dd66 100644
--- a/packages/views/locales/ru/billing.json
+++ b/packages/views/locales/ru/billing.json
@@ -338,6 +338,10 @@
"private_projects": {
"name": "Приватные проекты",
"after": "Остаются приватными после пробного периода. Списки доступа становятся доступны только для чтения."
+ },
+ "guests": {
+ "name": "Гости",
+ "after": "Текущие гости сохраняют доступ после пробного периода. Для приглашения новых гостей нужен Pro или Business."
}
}
}
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index a73cd561b8..3737decc33 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -629,7 +629,8 @@
"thread_nav_show_replies_many": "Показать {{count}} ответов",
"not_found_title": "Задача не найдена",
"load_failed": "Не удалось загрузить задачу.",
- "load_retry": "Повторить"
+ "load_retry": "Повторить",
+ "guest_readonly_note": "Гости могут просматривать и комментировать, но не могут менять свойства задачи."
},
"timeline": {
"loading": "Загрузка...",
@@ -838,7 +839,9 @@
"recipient_count_many": "{{count}} агентов получат это",
"reply_action": "Ответить",
"actions_label": "Действия с комментарием",
- "create_issue_from_selection": "Создать подзадачу из выделенного"
+ "create_issue_from_selection": "Создать подзадачу из выделенного",
+ "guest_placeholder": "Ответить… можно упомянуть участников через @",
+ "guest_hint": "Гости не могут упоминать агентов и назначать им задачи"
},
"reply": {
"recipients_changed": "Адресат ответа изменился. Проверьте получателей перед повторной отправкой.",
diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.json
index 088647d556..e8128bfb9a 100644
--- a/packages/views/locales/ru/layout.json
+++ b/packages/views/locales/ru/layout.json
@@ -168,7 +168,11 @@
"pinned_settings": "Отображение закреплённых",
"views_settings": "Отображение видов",
"views_builtin": "Встроенные виды",
- "views_show_count": "Счётчики"
+ "views_show_count": "Счётчики",
+ "guest_badge": "Гость",
+ "guest_badge_hint": "Вы можете просматривать и комментировать проекты, которыми с вами поделились.",
+ "involved": "С моим участием",
+ "shared_projects": "Доступные вам"
},
"team": {
"new_agent": "Новый агент",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index ed3be85934..d9e508499b 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -1640,6 +1640,10 @@
"member": {
"label": "Участник",
"description": "Создание задач и работа над ними"
+ },
+ "guest": {
+ "label": "Гость",
+ "description": "Просматривает и комментирует общие с ним проекты. Не может запускать агентов."
}
},
"share_links_create_title": "Создать ссылку для приглашения",
@@ -1689,7 +1693,32 @@
"toast_invitation_pending": "Приглашение для {{email}} уже ожидает ответа.",
"toast_invite_check_unavailable": "Не удалось проверить текущих участников и приглашения. Повторите попытку чуть позже.",
"member_limit_full_description_billing": "Подписке рабочего пространства нужно внимание. Восстановите её в разделе «Биллинг», чтобы добавлять участников, или сначала удалите участника.",
- "open_billing": "Открыть «Биллинг»"
+ "open_billing": "Открыть «Биллинг»",
+ "guest_free_tag": "Бесплатно · без места",
+ "guest_projects_label": "Доступные проекты",
+ "guest_projects_add": "Добавить проект…",
+ "guest_projects_remove": "Убрать {{project}}",
+ "guest_projects_hint": "Гости не видят другие проекты, агентов, автоматизации и настройки.",
+ "invite_guest_button": "Пригласить гостя",
+ "all_label": "Все",
+ "guests_label": "Гости",
+ "guest_count": "Гостей: {{count}}",
+ "list_separator": ", ",
+ "takes_seat": "Занимает 1 место",
+ "frees_seat": "Освобождает место",
+ "make_member": "Сделать участником",
+ "make_member_title": "Сделать {{name}} участником?",
+ "make_member_description": "{{name}} увидит всё рабочее пространство и сможет запускать агентов. Занимает 1 место.",
+ "make_member_seat_description": "{{name}} увидит всё рабочее пространство и сможет запускать агентов. Все места заняты, поэтому будет куплено ещё одно.",
+ "purchase_seat_and_make_member": "Купить место и сделать участником",
+ "making_member": "Меняем роль…",
+ "make_guest_title": "Сделать {{name}} гостем",
+ "make_guest_description": "{{name}} будет видеть только проекты ниже, место освободится. Его агенты, автоматизации и доступ к средам выполнения отзываются.",
+ "make_guest_button": "Сделать гостем",
+ "manage_projects": "Управлять доступными проектами",
+ "manage_projects_title": "Проекты, доступные {{name}}",
+ "save_projects": "Сохранить",
+ "toast_projects_updated": "Проекты обновлены"
},
"integrations": {
"status_connected": "Подключено",
diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.json
index b723e9dd5d..13e7ca8399 100644
--- a/packages/views/locales/zh-Hans/billing.json
+++ b/packages/views/locales/zh-Hans/billing.json
@@ -302,6 +302,10 @@
"private_projects": {
"name": "私有项目",
"after": "到期后保持私有,访问名单只读。"
+ },
+ "guests": {
+ "name": "访客",
+ "after": "到期后已有访客保留访问权限,邀请新访客需要 Pro 或 Business。"
}
}
}
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index e7e66c0781..2f6667c640 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -600,7 +600,8 @@
"workdir_path_unavailable": "暂无本地 workdir — 这个任务还没被本地智能体运行过",
"unsubscribe_subtree_succeeded": "已取消订阅此任务及其子任务。",
"subscription_update_failed": "无法更新订阅状态,请重试。",
- "pull_requests_empty_title": "暂无关联 PR。"
+ "pull_requests_empty_title": "暂无关联 PR。",
+ "guest_readonly_note": "访客可以查看和评论,不能修改任务属性。"
},
"timeline": {
"loading": "加载中…",
@@ -764,7 +765,9 @@
"restart_failed": "没能停止当前运行,消息还没有发送。",
"reply_action": "回复",
"actions_label": "评论操作",
- "create_issue_from_selection": "用选中内容创建子任务"
+ "create_issue_from_selection": "用选中内容创建子任务",
+ "guest_placeholder": "回复… 可以 @ 成员",
+ "guest_hint": "访客不能 @ 智能体,也不能分配任务给智能体"
},
"reply": {
"recipients_changed": "回复目标已变化。请重新确认接收者后再发送。",
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index 3f5acb6b1a..29163b0f66 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -188,7 +188,11 @@
"pinned_settings": "固定显示",
"views_settings": "视图显示",
"views_builtin": "内置视图",
- "views_show_count": "数量"
+ "views_show_count": "数量",
+ "guest_badge": "访客",
+ "guest_badge_hint": "你可以查看和评论分享给你的项目。",
+ "involved": "我参与的",
+ "shared_projects": "分享给你的项目"
},
"team": {
"new_agent": "新建智能体",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index e1ea80858c..b29ec11b01 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1596,6 +1596,10 @@
"member": {
"label": "成员",
"description": "创建并处理任务"
+ },
+ "guest": {
+ "label": "访客",
+ "description": "只能查看和评论分享给他的项目,不能运行智能体。"
}
},
"share_links_create_title": "创建分享链接",
@@ -1645,7 +1649,32 @@
"toast_invitation_pending": "已经有一封发给 {{email}} 的待接受邀请。",
"toast_invite_check_unavailable": "暂时无法核对现有成员和邀请,请稍后再试。",
"member_limit_full_description_billing": "工作区的订阅需要处理。到「账单与套餐」恢复订阅后才能加人,也可以先移除一位成员。",
- "open_billing": "打开账单与套餐"
+ "open_billing": "打开账单与套餐",
+ "guest_free_tag": "免费 · 不占席位",
+ "guest_projects_label": "可以访问的项目",
+ "guest_projects_add": "添加项目…",
+ "guest_projects_remove": "移除 {{project}}",
+ "guest_projects_hint": "访客看不到其他项目、智能体、自动化和设置。",
+ "invite_guest_button": "邀请访客",
+ "all_label": "全部",
+ "guests_label": "访客",
+ "guest_count": "{{count}} 位访客",
+ "list_separator": "、",
+ "takes_seat": "占 1 个席位",
+ "frees_seat": "不占席位",
+ "make_member": "转为成员",
+ "make_member_title": "把 {{name}} 转为成员?",
+ "make_member_description": "{{name}} 可以访问整个工作区、运行智能体,会占用 1 个席位。",
+ "make_member_seat_description": "{{name}} 可以访问整个工作区、运行智能体。已购席位已用完,将补购 1 个席位。",
+ "purchase_seat_and_make_member": "补购席位并转为成员",
+ "making_member": "正在转为成员…",
+ "make_guest_title": "把 {{name}} 转为访客",
+ "make_guest_description": "{{name}} 之后只能访问下面的项目,并释放 1 个席位。他的智能体、自动化和运行时权限会被收回。",
+ "make_guest_button": "转为访客",
+ "manage_projects": "管理可访问的项目",
+ "manage_projects_title": "{{name}} 可以访问的项目",
+ "save_projects": "保存",
+ "toast_projects_updated": "已更新可访问的项目"
},
"integrations": {
"status_connected": "已连接",
diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.json
index e76dea0d30..3e477109b2 100644
--- a/packages/views/locales/zh-Hant/billing.json
+++ b/packages/views/locales/zh-Hant/billing.json
@@ -302,6 +302,10 @@
"private_projects": {
"name": "私有專案",
"after": "到期後保持私有,存取名單唯讀。"
+ },
+ "guests": {
+ "name": "訪客",
+ "after": "到期後既有訪客保留存取權限,邀請新訪客需要 Pro 或 Business。"
}
}
}
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 94ec3f00b5..1d88f3ee6d 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -600,7 +600,8 @@
"workdir_path_unavailable": "暫無本地 workdir — 這個任務還沒被本地 AI 代理執行過",
"unsubscribe_subtree_succeeded": "已取消訂閱此任務及其子任務。",
"subscription_update_failed": "無法更新訂閱狀態,請重試。",
- "pull_requests_empty_title": "暫無關聯 PR。"
+ "pull_requests_empty_title": "暫無關聯 PR。",
+ "guest_readonly_note": "訪客可以查看和評論,不能修改任務屬性。"
},
"timeline": {
"loading": "載入中…",
@@ -764,7 +765,9 @@
"restart_failed": "沒能停止當前執行,訊息還沒有傳送。",
"reply_action": "回覆",
"actions_label": "評論操作",
- "create_issue_from_selection": "用選取內容建立子任務"
+ "create_issue_from_selection": "用選取內容建立子任務",
+ "guest_placeholder": "回覆… 可以 @ 成員",
+ "guest_hint": "訪客不能 @ 智慧體,也不能分配任務給智慧體"
},
"reply": {
"recipients_changed": "回覆目標已變更。請重新確認收件者後再傳送。",
diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.json
index f51398ea0d..3157524e84 100644
--- a/packages/views/locales/zh-Hant/layout.json
+++ b/packages/views/locales/zh-Hant/layout.json
@@ -188,7 +188,11 @@
"pinned_settings": "固定顯示",
"views_settings": "檢視顯示",
"views_builtin": "內建檢視",
- "views_show_count": "數量"
+ "views_show_count": "數量",
+ "guest_badge": "訪客",
+ "guest_badge_hint": "你可以查看和評論分享給你的專案。",
+ "involved": "我參與的",
+ "shared_projects": "分享給你的專案"
},
"team": {
"new_agent": "新建 AI 代理",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 38fc546539..24b84deab9 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -1596,6 +1596,10 @@
"member": {
"label": "成員",
"description": "建立並處理任務"
+ },
+ "guest": {
+ "label": "訪客",
+ "description": "只能查看和評論分享給他的專案,不能執行智慧體。"
}
},
"share_links_create_title": "建立分享連結",
@@ -1645,7 +1649,32 @@
"toast_invitation_pending": "已經有一封發給 {{email}} 的待接受邀請。",
"toast_invite_check_unavailable": "暫時無法核對現有成員和邀請,請稍後再試。",
"member_limit_full_description_billing": "工作區的訂閱需要處理。到「帳單與套餐」恢復訂閱後才能加人,也可以先移除一位成員。",
- "open_billing": "開啟帳單與套餐"
+ "open_billing": "開啟帳單與套餐",
+ "guest_free_tag": "免費 · 不佔席位",
+ "guest_projects_label": "可以存取的專案",
+ "guest_projects_add": "新增專案…",
+ "guest_projects_remove": "移除 {{project}}",
+ "guest_projects_hint": "訪客看不到其他專案、智慧體、自動化和設定。",
+ "invite_guest_button": "邀請訪客",
+ "all_label": "全部",
+ "guests_label": "訪客",
+ "guest_count": "{{count}} 位訪客",
+ "list_separator": "、",
+ "takes_seat": "佔 1 個席位",
+ "frees_seat": "不佔席位",
+ "make_member": "轉為成員",
+ "make_member_title": "把 {{name}} 轉為成員?",
+ "make_member_description": "{{name}} 可以存取整個工作區、執行智慧體,會佔用 1 個席位。",
+ "make_member_seat_description": "{{name}} 可以存取整個工作區、執行智慧體。已購席位已用完,將補購 1 個席位。",
+ "purchase_seat_and_make_member": "補購席位並轉為成員",
+ "making_member": "正在轉為成員…",
+ "make_guest_title": "把 {{name}} 轉為訪客",
+ "make_guest_description": "{{name}} 之後只能存取下面的專案,並釋放 1 個席位。他的智慧體、自動化和執行環境權限會被收回。",
+ "make_guest_button": "轉為訪客",
+ "manage_projects": "管理可存取的專案",
+ "manage_projects_title": "{{name}} 可以存取的專案",
+ "save_projects": "儲存",
+ "toast_projects_updated": "已更新可存取的專案"
},
"integrations": {
"status_connected": "已連線",
diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsx
index 22946fcf0b..14368b9add 100644
--- a/packages/views/my-issues/components/my-issues-page.tsx
+++ b/packages/views/my-issues/components/my-issues-page.tsx
@@ -31,16 +31,18 @@ export function MyIssuesPage() {
modes={["board", "list", "table", "swimlane"]}
batchToolbar="list"
renderHeader={({ controller }) => <IssueViewHeader controller={controller} base={MY_BASE} />}
- renderEmpty={({ controller }) => (
+ renderEmpty={({ controller, canCreate }) => (
<CollectionPageState
icon={CircleUser}
title={t(($) => $.page.empty_title)}
description={t(($) => $.page.empty_description)}
actions={
- <Button size="sm" onClick={() => controller.openCreateIssue()}>
- <Plus aria-hidden="true" />
- {tIssues(($) => $.views.new_issue)}
- </Button>
+ canCreate && (
+ <Button size="sm" onClick={() => controller.openCreateIssue()}>
+ <Plus aria-hidden="true" />
+ {tIssues(($) => $.views.new_issue)}
+ </Button>
+ )
}
/>
)}
diff --git a/packages/views/search/commands/context-commands.tsx b/packages/views/search/commands/context-commands.tsx
index 1c70e811a3..818e31b1cb 100644
--- a/packages/views/search/commands/context-commands.tsx
+++ b/packages/views/search/commands/context-commands.tsx
@@ -28,7 +28,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
import { useModalStore } from "@multica/core/modals";
import { useWorkspacePaths } from "@multica/core/paths";
-import { canAssignAgentToIssue, useCurrentMember } from "@multica/core/permissions";
+import { canAssignAgentToIssue, useCurrentMember, useIsGuest } from "@multica/core/permissions";
import { pinListOptions, useCreatePin, useDeletePin } from "@multica/core/pins";
import { getShortcut } from "@multica/core/shortcuts";
import { copyText } from "@multica/ui/lib/clipboard";
@@ -54,6 +54,7 @@ export function useProjectCommandGroup(
});
const createPin = useCreatePin();
const deletePin = useDeletePin();
+ const guest = useIsGuest(wsId);
return useMemo(() => {
if (!context) return null;
@@ -69,14 +70,19 @@ export function useProjectCommandGroup(
crumb: project.title,
primary: true,
},
- {
- id: "project-new-issue",
- label: t(($) => $.project.new_issue),
- icon: SquarePen,
- keywords: ["new", "issue", "create", "新建", "任务"],
- run: () => openCreateIssueWithPreference({ project_id: project.id }),
- primary: true,
- },
+ // A guest (MUL-9420) cannot create issues.
+ ...(guest
+ ? []
+ : [
+ {
+ id: "project-new-issue",
+ label: t(($) => $.project.new_issue),
+ icon: SquarePen,
+ keywords: ["new", "issue", "create", "新建", "任务"],
+ run: () => openCreateIssueWithPreference({ project_id: project.id }),
+ primary: true,
+ },
+ ]),
{
id: "project-pin",
label: pinned ? t(($) => $.project.unpin) : t(($) => $.project.pin),
@@ -105,7 +111,7 @@ export function useProjectCommandGroup(
heading: <ContextHeading label={t(($) => $.context.current_project)} subject={project.title} />,
commands,
};
- }, [context, createPin, deletePin, getShareableUrl, p, pins, t]);
+ }, [context, createPin, deletePin, getShareableUrl, guest, p, pins, t]);
}
export function useAgentCommandGroup(context: ContextOf<"agent"> | null): PaletteCommandGroup | null {
diff --git a/packages/views/search/commands/global-commands.tsx b/packages/views/search/commands/global-commands.tsx
index 72dd55d9a2..c4be868f03 100644
--- a/packages/views/search/commands/global-commands.tsx
+++ b/packages/views/search/commands/global-commands.tsx
@@ -17,7 +17,8 @@ import type { CommandBarContext } from "@multica/core/command-bar";
import { useArchiveAllReadInbox, useMarkAllInboxRead } from "@multica/core/inbox/mutations";
import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
import { useModalStore } from "@multica/core/modals";
-import { useWorkspacePaths } from "@multica/core/paths";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { useIsGuest } from "@multica/core/permissions";
import { useShortcut } from "@multica/core/shortcuts";
import { isFloatingChatRouteSuppressed } from "../../chat/floating-chat-visibility";
import { useNavigation } from "../../navigation";
@@ -39,6 +40,8 @@ export function useGlobalCommands(contexts: readonly CommandBarContext[]): Palet
const toggleChatShortcut = useShortcut("toggleChat");
const markAllRead = useMarkAllInboxRead();
const archiveAllRead = useArchiveAllReadInbox();
+ // A guest (MUL-9420) cannot create issues.
+ const guest = useIsGuest(useCurrentWorkspace()?.id);
const projectContext = contexts.find((c) => c.kind === "project");
const projectId = projectContext?.kind === "project" ? projectContext.project.id : null;
@@ -48,16 +51,21 @@ export function useGlobalCommands(contexts: readonly CommandBarContext[]): Palet
return useMemo<PaletteCommand[]>(() => {
const chatPath = p.chat();
+ const newIssue: PaletteCommand[] = guest
+ ? []
+ : [
+ {
+ id: "new-issue",
+ label: t(($) => $.commands.new_issue),
+ icon: SquarePen,
+ keywords: ["new", "issue", "create", "add", "新建", "任务"],
+ shortcut: createIssueShortcut,
+ run: () => openCreateIssueWithPreference(projectId ? { project_id: projectId } : undefined),
+ primary: true,
+ },
+ ];
return [
- {
- id: "new-issue",
- label: t(($) => $.commands.new_issue),
- icon: SquarePen,
- keywords: ["new", "issue", "create", "add", "新建", "任务"],
- shortcut: createIssueShortcut,
- run: () => openCreateIssueWithPreference(projectId ? { project_id: projectId } : undefined),
- primary: true,
- },
+ ...newIssue,
{
id: "chat-with-agent",
label: t(($) => $.commands.chat_with_agent),
@@ -146,6 +154,7 @@ export function useGlobalCommands(contexts: readonly CommandBarContext[]): Palet
}, [
archiveAllRead,
createIssueShortcut,
+ guest,
inbox,
markAllRead,
navigation,
diff --git a/packages/views/search/root-view.tsx b/packages/views/search/root-view.tsx
index f9132fcf4b..ca635e162e 100644
--- a/packages/views/search/root-view.tsx
+++ b/packages/views/search/root-view.tsx
@@ -13,6 +13,7 @@ import { projectListOptions } from "@multica/core/projects/queries";
import type { InboxWorkspaceUnread } from "@multica/core/types";
import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
import { useModalStore } from "@multica/core/modals";
+import { useIsGuest } from "@multica/core/permissions";
import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "../common/actor-avatar";
import { BUILTIN_VIEW_ICON, useBuiltinViewNavigation } from "../issue-views/builtin-views";
@@ -63,6 +64,8 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri
const p = useWorkspacePaths();
const { data: unreadSummary = EMPTY_UNREAD_SUMMARY } = useQuery(inboxUnreadSummaryOptions());
const unreadWsIds = unreadWorkspaceIds(unreadSummary);
+ // A guest (MUL-9420) can neither create issues nor hand work to an agent.
+ const guest = useIsGuest(useWorkspaceId());
const { server, partitioned, objects, text } = model;
const query = text;
@@ -409,7 +412,7 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri
return (
<>
- {best && <BestMatchGroups best={best} query={query} target={model.primaryIssueTarget} />}
+ {best && <BestMatchGroups best={best} query={query} target={model.primaryIssueTarget} canCreateIssue={!guest} />}
{groups.map((group) => group.node)}
{partitioned.hasCancelled && (
<PaletteGroup heading={t(($) => $.groups.cancelled)}>
@@ -447,7 +450,7 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri
{!server.isLoading && nothing && (
<div className="py-10 text-center text-body text-muted-foreground">{t(($) => $.empty.no_results)}</div>
)}
- {model.handToAgent && <HandToAgentRow seed={model.handToAgent} disabled={server.stale} />}
+ {model.handToAgent && !guest && <HandToAgentRow seed={model.handToAgent} disabled={server.stale} />}
</>
);
}
@@ -543,10 +546,12 @@ function BestMatchGroups({
best,
query,
target,
+ canCreateIssue,
}: {
best: BestMatch;
query: string;
target: IssueTarget | null;
+ canCreateIssue: boolean;
}) {
const { t } = useT("search");
const palette = usePalette();
@@ -641,7 +646,7 @@ function BestMatchGroups({
trailing={<RowHint>{t(($) => $.types.project)}</RowHint>}
/>
);
- if (!project.archived_at) {
+ if (!project.archived_at && canCreateIssue) {
actions.push({
id: "new-issue",
label: t(($) => $.best.new_issue_in, { name: project.title }),
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index daf6afe89c..70c813eb4f 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -424,6 +424,39 @@ describe("SearchCommand", () => {
expect(renderedValues()).toEqual(["command:new-issue", "command:chat-with-agent"]);
});
+ describe("guest (MUL-9420)", () => {
+ beforeEach(() => {
+ seed(memberListOptions("ws-test"), [{ ...makeMember(ME, "Me Myself", "[email protected]"), role: "guest" }]);
+ });
+
+ it("offers no New issue on an empty query", () => {
+ renderSearch();
+
+ expect(renderedValues()).not.toContain("command:new-issue");
+ });
+
+ it("finds no New issue command and no hand-to-agent row while typing", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "new");
+
+ expect(await rowText("New project")).toBeInTheDocument();
+ expect(screen.queryByText((_, el) => el?.textContent === "New issue" && el?.tagName === "SPAN")).toBeNull();
+ expect(renderedValues()).not.toContain("hand-to-agent");
+ });
+
+ it("drops New issue from a project's context commands", () => {
+ registerContext({
+ kind: "project",
+ project: { id: "proj-1", title: "Shared project", archived_at: null },
+ } as CommandBarContext);
+ renderSearch();
+
+ expect(renderedValues()).toContain("command:context-project:project-status");
+ expect(renderedValues()).not.toContain("command:context-project:project-new-issue");
+ });
+ });
+
describe("pages and global commands", () => {
it("filters navigation pages by query", async () => {
const user = userEvent.setup();
diff --git a/packages/views/settings/components/billing-trial-section.tsx b/packages/views/settings/components/billing-trial-section.tsx
index 4f325ea428..43f46d0256 100644
--- a/packages/views/settings/components/billing-trial-section.tsx
+++ b/packages/views/settings/components/billing-trial-section.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Lock, Sparkles } from "@multica/ui/icons";
+import { Eye, Lock, Sparkles } from "@multica/ui/icons";
import { resolveWorkspaceTrial } from "@multica/core/billing/trial";
import type { PaidFeature, WorkspaceSubscriptionSummary } from "@multica/core/types";
import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";
@@ -13,6 +13,7 @@ import { SettingsCard, SettingsRow, SettingsSection } from "./settings-layout";
const TRIAL_FEATURE_ICONS: Record<PaidFeature, IconComponent> = {
private_projects: Lock,
+ guests: Eye,
};
const TRIAL_FEATURES = Object.keys(TRIAL_FEATURE_ICONS) as PaidFeature[];
diff --git a/packages/views/settings/components/guest-projects.tsx b/packages/views/settings/components/guest-projects.tsx
new file mode 100644
index 0000000000..aa521415fb
--- /dev/null
+++ b/packages/views/settings/components/guest-projects.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Plus, X } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { Label } from "@multica/ui/components/ui/label";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { Project } from "@multica/core/types";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { useT } from "../../i18n";
+
+/** Projects an admin can share with a guest: the live ones it can see. */
+export function useShareableProjects(wsId: string): Project[] {
+ const { data } = useQuery(projectListOptions(wsId));
+ return (data ?? []).filter((project) => !project.archived_at);
+}
+
+/**
+ * The projects a guest (MUL-9420) can see, as removable chips with an
+ * "Add project…" menu. A guest needs at least one.
+ */
+export function GuestProjectsField({
+ id,
+ projects,
+ value,
+ onChange,
+}: {
+ id: string;
+ projects: Project[];
+ value: string[];
+ onChange: (next: string[]) => void;
+}) {
+ const { t } = useT("settings");
+ const byId = new Map(projects.map((project) => [project.id, project]));
+ const selected = value.map((projectId) => byId.get(projectId)).filter((p): p is Project => !!p);
+ const remaining = projects.filter((project) => !value.includes(project.id));
+
+ return (
+ <div className="space-y-1.5">
+ <Label id={id}>{t(($) => $.members.guest_projects_label)}</Label>
+ <div
+ role="group"
+ aria-labelledby={id}
+ className="flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border border-input px-2 py-1.5"
+ >
+ {selected.map((project) => (
+ <span
+ key={project.id}
+ className="inline-flex h-6 items-center gap-1 rounded-md bg-muted pr-1 pl-1.5 text-caption font-medium"
+ >
+ <ProjectIcon project={project} />
+ <span className="max-w-40 truncate">{project.title}</span>
+ <button
+ type="button"
+ className="inline-flex size-4 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-hover hover:text-foreground"
+ aria-label={t(($) => $.members.guest_projects_remove, { project: project.title })}
+ onClick={() => onChange(value.filter((projectId) => projectId !== project.id))}
+ >
+ <X className="size-3" />
+ </button>
+ </span>
+ ))}
+ {remaining.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ className="inline-flex h-6 items-center gap-1 rounded-md px-1.5 text-caption text-muted-foreground hover:bg-surface-hover hover:text-foreground"
+ >
+ <Plus className="size-3" />
+ {t(($) => $.members.guest_projects_add)}
+ </button>
+ }
+ />
+ <DropdownMenuContent align="start" className="max-h-72 w-56 overflow-y-auto">
+ {remaining.map((project) => (
+ <DropdownMenuItem key={project.id} onClick={() => onChange([...value, project.id])}>
+ <ProjectIcon project={project} />
+ <span className="truncate">{project.title}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ <p className="text-caption text-muted-foreground">{t(($) => $.members.guest_projects_hint)}</p>
+ </div>
+ );
+}
+
+/**
+ * Picks a guest's projects, either to change them or to turn a member into a
+ * guest. The caller does the request; a failure keeps the dialog open.
+ */
+export function GuestProjectsDialog({
+ open,
+ title,
+ description,
+ confirmLabel,
+ projects,
+ initial,
+ onOpenChange,
+ onConfirm,
+}: {
+ open: boolean;
+ title: string;
+ description?: string;
+ confirmLabel: string;
+ projects: Project[];
+ initial: string[];
+ onOpenChange: (open: boolean) => void;
+ onConfirm: (projectIds: string[]) => Promise<void>;
+}) {
+ const { t } = useT("settings");
+ const [value, setValue] = useState(initial);
+ const [saving, setSaving] = useState(false);
+ useEffect(() => {
+ if (open) setValue(initial);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reset on open only
+ }, [open]);
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!saving) onOpenChange(next);
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ {description ? <DialogDescription>{description}</DialogDescription> : null}
+ </DialogHeader>
+ <GuestProjectsField id="guest-projects-dialog" projects={projects} value={value} onChange={setValue} />
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
+ {t(($) => $.members.confirm_cancel)}
+ </Button>
+ <Button
+ type="button"
+ disabled={saving || value.length === 0}
+ aria-busy={saving || undefined}
+ onClick={async () => {
+ setSaving(true);
+ try {
+ await onConfirm(value);
+ } finally {
+ setSaving(false);
+ }
+ }}
+ >
+ {confirmLabel}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/settings/components/members-tab.test.tsx b/packages/views/settings/components/members-tab.test.tsx
index b41aedbf20..b15e30bd96 100644
--- a/packages/views/settings/components/members-tab.test.tsx
+++ b/packages/views/settings/components/members-tab.test.tsx
@@ -46,6 +46,7 @@ vi.mock("@tanstack/react-query", () => ({
}
if (key.includes("share-links")) return { data: data.shareLinks };
if (key.includes("members")) return { data: data.members, isSuccess: true };
+ if (key.includes("projects")) return { data: [] };
return { data: data.summary };
},
useQueryClient: () => ({
diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsx
index 1c0d91c790..da29f80e83 100644
--- a/packages/views/settings/components/members-tab.tsx
+++ b/packages/views/settings/components/members-tab.tsx
@@ -5,6 +5,8 @@ import {
Check,
Copy,
Crown,
+ Eye,
+ FolderOpen,
Link,
Loader2,
Mail,
@@ -28,6 +30,7 @@ import type {
ShareLink,
WorkspaceSeatPurchasePreview,
} from "@multica/core/types";
+import { cn } from "@multica/ui/lib/utils";
import { Input } from "@multica/ui/components/ui/input";
import { Button } from "@multica/ui/components/ui/button";
import { IconButton } from "@multica/ui/components/common/icon-button";
@@ -63,11 +66,10 @@ import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
+ DropdownMenuGroup,
DropdownMenuItem,
+ DropdownMenuLabel,
DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubTrigger,
- DropdownMenuSubContent,
} from "@multica/ui/components/ui/dropdown-menu";
import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";
import { toast } from "sonner";
@@ -83,12 +85,17 @@ import {
saveUpgradeInvite,
type UpgradeInvite,
usePreviewWorkspaceSeatPurchase,
+ refreshFeaturesOnLockedError,
+ usePaidFeatureAccess,
usePurchaseWorkspaceSeats,
workspaceSubscriptionSummaryOptions,
} from "@multica/core/billing";
import { useWorkspaceId } from "@multica/core/hooks";
import { useFeatureEnabled } from "@multica/core/config";
-import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
+import {
+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
+ WORKSPACE_GUESTS_FLAG,
+} from "@multica/core/feature-flags";
import { useCurrentWorkspace } from "@multica/core/paths";
import {
invitationListOptions,
@@ -107,6 +114,8 @@ import {
} from "./settings-layout";
import { resolveSettingsLocation, settingsHref } from "./settings-navigation";
import { formatStripeMinorAmount } from "./billing-format";
+import { PaidFeatureNotice, usePaidFeatureErrorMessage } from "../../billing";
+import { GuestProjectsDialog, GuestProjectsField, useShareableProjects } from "./guest-projects";
import {
isSingleSeatInvitePreview,
purchasedSeatIsReadyForInvitation,
@@ -127,12 +136,16 @@ const HELD_INVITE_RETRY_MS = 6_000;
// Catches typos before an upgrade buys a seat for the invitation.
const INVITE_EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
-type MembersView = "members" | "invitations" | "links";
+// "members" lists everyone; with guests on, "seated" and "guests" split it.
+type MembersView = "members" | "seated" | "guests" | "invitations" | "links";
+// A seat bought to invite someone, or to turn a guest into a member.
type InviteSeatPurchase = {
workspaceId: string;
email: string;
role: MemberRole;
+ projectIds?: string[];
+ promote?: { memberId: string; name: string };
preview: WorkspaceSeatPurchasePreview;
idempotencyKey: string;
phase: "review" | "purchasing" | "waiting" | "inviting" | "error";
@@ -152,6 +165,7 @@ const ROLE_ICONS: Record<MemberRole, typeof Crown> = {
owner: Crown,
admin: Shield,
member: User,
+ guest: Eye,
};
// Builds the shareable URL for a share-link invite. Prefers the navigation
@@ -186,6 +200,11 @@ function useRoleLabels() {
description: t(($) => $.members.roles.member.description),
icon: ROLE_ICONS.member,
},
+ guest: {
+ label: t(($) => $.members.roles.guest.label),
+ description: t(($) => $.members.roles.guest.description),
+ icon: ROLE_ICONS.guest,
+ },
} as const;
}
@@ -193,21 +212,29 @@ function MemberRow({
member,
canManage,
canManageOwners,
+ guestsEnabled,
+ projectNames,
ownerCount,
isSelf,
busy,
onRoleChange,
+ onManageProjects,
onRemove,
}: {
member: MemberWithUser;
canManage: boolean;
canManageOwners: boolean;
+ /** Whether a member can be turned into a guest. */
+ guestsEnabled: boolean;
+ /** A guest's projects, shown beside its name. */
+ projectNames: string[];
/** Total number of owners in this workspace — needed to gate demoting the
* last owner per `workspace.go:497-507`. */
ownerCount: number;
isSelf: boolean;
busy: boolean;
onRoleChange: (role: MemberRole) => void;
+ onManageProjects: () => void;
onRemove: () => void;
}) {
const { t } = useT("settings");
@@ -218,7 +245,15 @@ function MemberRow({
const canEditRole = canManage && !isSelf && (member.role !== "owner" || canManageOwners);
const canRemove = canManage && !isSelf && (member.role !== "owner" || canManageOwners);
const isLastOwner = member.role === "owner" && ownerCount <= 1;
+ const isGuest = member.role === "guest";
const showMenu = canEditRole || canRemove;
+ // A guest becomes a member or admin first; ownership is not handed over
+ // in the same step.
+ const roleOptions = (Object.keys(roleConfig) as MemberRole[]).filter(
+ (role) =>
+ (role !== "owner" || (canManageOwners && !isGuest)) &&
+ (role !== "guest" || guestsEnabled || isGuest),
+ );
return (
<div className="flex items-center gap-3 px-4 py-3">
@@ -231,6 +266,11 @@ function MemberRow({
{t(($) => $.members.you)}
</Badge>
) : null}
+ {isGuest && projectNames.length > 0 ? (
+ <span className="truncate text-caption text-muted-foreground">
+ {projectNames.join(t(($) => $.members.list_separator))}
+ </span>
+ ) : null}
</div>
<div className="truncate text-caption text-muted-foreground">{member.email}</div>
</div>
@@ -258,51 +298,56 @@ function MemberRow({
</IconButton>
}
/>
- <DropdownMenuContent align="end" className="w-auto">
+ <DropdownMenuContent align="end" className="w-60">
{canEditRole && (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Shield className="h-3.5 w-3.5" />
- {t(($) => $.members.change_role)}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto">
- {(Object.entries(roleConfig) as [MemberRole, (typeof roleConfig)[MemberRole]][]).map(
- ([role, config]) => {
- if (role === "owner" && !canManageOwners) return null;
- const Icon = config.icon;
- const wouldDemoteLastOwner =
- isLastOwner && role !== "owner";
- return (
- <DropdownMenuItem
- key={role}
- onClick={() =>
- wouldDemoteLastOwner ? undefined : onRoleChange(role)
- }
- disabled={wouldDemoteLastOwner}
- title={
- wouldDemoteLastOwner
- ? t(($) => $.members.cannot_demote_last_owner_title)
- : undefined
- }
- >
- <Icon className="h-3.5 w-3.5" />
- <div className="flex flex-col">
- <span>{config.label}</span>
- <span className="text-caption text-muted-foreground font-normal">
- {wouldDemoteLastOwner
- ? t(($) => $.members.cannot_demote_last_owner)
- : config.description}
- </span>
- </div>
- {member.role === role && (
- <Check className="ml-auto size-3.5 text-muted-foreground" />
- )}
- </DropdownMenuItem>
- );
- }
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.members.change_role)}</DropdownMenuLabel>
+ {roleOptions.map((role) => {
+ const Icon = roleConfig[role].icon;
+ const current = member.role === role;
+ const wouldDemoteLastOwner = isLastOwner && role !== "owner";
+ // Moving across the guest line takes or frees a seat.
+ const seatHint =
+ isGuest && role === "member"
+ ? t(($) => $.members.takes_seat)
+ : !isGuest && role === "guest"
+ ? t(($) => $.members.frees_seat)
+ : null;
+ return (
+ <DropdownMenuItem
+ key={role}
+ onClick={() => {
+ if (!current && !wouldDemoteLastOwner) onRoleChange(role);
+ }}
+ disabled={wouldDemoteLastOwner}
+ title={
+ wouldDemoteLastOwner
+ ? t(($) => $.members.cannot_demote_last_owner_title)
+ : roleConfig[role].description
+ }
+ >
+ {current ? <Check className="h-3.5 w-3.5" /> : <Icon className="h-3.5 w-3.5" />}
+ <span>
+ {isGuest && role === "member"
+ ? t(($) => $.members.make_member)
+ : roleConfig[role].label}
+ </span>
+ {seatHint ? (
+ <span className="ml-auto pl-3 text-caption text-muted-foreground">{seatHint}</span>
+ ) : null}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuGroup>
+ )}
+ {canEditRole && isGuest && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={onManageProjects}>
+ <FolderOpen className="h-3.5 w-3.5" />
+ {t(($) => $.members.manage_projects)}
+ </DropdownMenuItem>
+ </>
)}
{canEditRole && canRemove && <DropdownMenuSeparator />}
{canRemove && (
@@ -451,7 +496,10 @@ export function MembersTab() {
navigation?.searchParams ?? new URLSearchParams(),
).section;
const urlView: MembersView =
- requestedView === "invitations" || requestedView === "links"
+ requestedView === "invitations" ||
+ requestedView === "links" ||
+ requestedView === "seated" ||
+ requestedView === "guests"
? requestedView
: "members";
const [localView, setLocalView] = useState<MembersView>(urlView);
@@ -472,6 +520,12 @@ export function MembersTab() {
const [memberQuery, setMemberQuery] = useState("");
const [inviteEmail, setInviteEmail] = useState("");
const [inviteRole, setInviteRole] = useState<MemberRole>("member");
+ const [inviteProjects, setInviteProjects] = useState<string[]>([]);
+ // Turning a member into a guest, or changing a guest's projects.
+ const [projectsDialog, setProjectsDialog] = useState<{
+ member: MemberWithUser;
+ mode: "demote" | "edit";
+ } | null>(null);
const [inviteLoading, setInviteLoading] = useState(false);
const [inviteSeatPurchase, setInviteSeatPurchase] =
useState<InviteSeatPurchase | null>(null);
@@ -486,6 +540,7 @@ export function MembersTab() {
title: string;
description: string;
variant?: "destructive";
+ actionLabel?: string;
onConfirm: () => Promise<void>;
} | null>(null);
const previewSeatPurchase = usePreviewWorkspaceSeatPurchase();
@@ -565,24 +620,47 @@ export function MembersTab() {
subscriptionSummary?.availableActions.checkout === false;
const canUpgradeForInvite =
inviteBlockedByMemberLimit && billingEnabled && !subscriptionNeedsAttention;
+ const guestsEnabled = useFeatureEnabled(WORKSPACE_GUESTS_FLAG, false);
+ // Guests are a paid feature: a plan without them keeps its existing guests
+ // (they can be removed, narrowed or made members) but adds no new ones.
+ const guestAccess = usePaidFeatureAccess(wsId, "guests", { hasExistingConfig: false });
+ const canAddGuests = guestsEnabled && guestAccess.canAdd;
+ const paidFeatureError = usePaidFeatureErrorMessage();
+ const shareableProjects = useShareableProjects(wsId);
+ const projectTitles = new Map(shareableProjects.map((project) => [project.id, project.title]));
+ const guestCount = members.filter((m) => m.role === "guest").length;
+ // Workspaces that already have guests keep seeing them if the flag goes off.
+ const showGuestViews = guestsEnabled || guestCount > 0;
+ // A guest takes no member slot, so a full workspace still invites guests.
+ const inviteLimited = inviteRole !== "guest";
+ const inviteFull = inviteLimited && inviteBlockedByMemberLimit;
+ const inviteNeedsAttention = inviteLimited && subscriptionNeedsAttention;
+ const inviteCanUpgrade = inviteLimited && canUpgradeForInvite;
+ const guestInviteMissingProjects = inviteRole === "guest" && inviteProjects.length === 0;
const needle = memberQuery.trim().toLocaleLowerCase();
- const visibleMembers = needle
- ? members.filter(
- (m) =>
- m.name.toLocaleLowerCase().includes(needle) ||
- m.email.toLocaleLowerCase().includes(needle),
- )
- : members;
+ const peopleView = showGuestViews && (view === "seated" || view === "guests") ? view : "members";
+ const visibleMembers = members.filter(
+ (m) =>
+ (peopleView !== "seated" || m.role !== "guest") &&
+ (peopleView !== "guests" || m.role === "guest") &&
+ (!needle ||
+ m.name.toLocaleLowerCase().includes(needle) ||
+ m.email.toLocaleLowerCase().includes(needle)),
+ );
const sendInvitation = useCallback(
- async (email: string, role: MemberRole) => {
+ async (email: string, role: MemberRole, projectIds?: string[]) => {
if (!workspace) return;
- await api.createMember(workspace.id, { email, role });
+ await api.createMember(
+ workspace.id,
+ role === "guest" ? { email, role, project_ids: projectIds } : { email, role },
+ );
// The invitation is out, however it was sent (directly, after an
// upgrade, or after buying a seat): nothing held for it still waits.
clearUpgradeInvitesFor(workspace.slug, email);
setInviteEmail("");
setInviteRole("member");
+ setInviteProjects([]);
await qc.invalidateQueries({
queryKey: workspaceKeys.invitations(wsId),
});
@@ -591,20 +669,127 @@ export function MembersTab() {
[qc, t, workspace, wsId],
);
+ const changeRole = useCallback(
+ async (memberId: string, role: MemberRole, projectIds?: string[]) => {
+ if (!workspace) return;
+ await api.updateMember(
+ workspace.id,
+ memberId,
+ role === "guest" ? { role, project_ids: projectIds } : { role },
+ );
+ await qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });
+ // Crossing the guest line takes or frees a member slot.
+ void qc.invalidateQueries({ queryKey: memberLimitKeys.all(wsId) });
+ toast.success(t(($) => $.members.toast_role_updated));
+ },
+ [qc, t, workspace, wsId],
+ );
+
+ /**
+ * Handles a refusal for lack of a seat, from an invitation or from turning a
+ * guest into a member: offers to buy one when the workspace is full.
+ * Returns false when the error is not about seats.
+ */
+ const handleSeatRefusal = async (
+ e: unknown,
+ request: Pick<InviteSeatPurchase, "email" | "role" | "projectIds" | "promote">,
+ ): Promise<boolean> => {
+ if (!workspace) return true;
+ const code = errorCode(e);
+ const capacityFailure = seatInvitationCapacityFailure(code);
+ if (code === "seat_capacity_overcommitted") {
+ try {
+ const summary = await qc.fetchQuery({
+ ...workspaceSubscriptionSummaryOptions(wsId),
+ staleTime: 0,
+ });
+ const capacity = summary?.seatCapacity;
+ toast.error(
+ billingT(($) => $.workspace.seats.members_over_capacity_title),
+ capacity
+ ? {
+ description: billingT(
+ ($) => $.workspace.seats.occupancy_over_capacity_description,
+ {
+ // Cloud refuses on used + reserved, so pending
+ // invitations have to appear here: the most common
+ // trigger is a first ledger snapshot whose member count
+ // alone still fits inside the purchased seats.
+ occupied: capacity.used + capacity.reserved,
+ purchased: capacity.purchased,
+ members: capacity.used,
+ reserved: capacity.reserved,
+ },
+ ),
+ }
+ : undefined,
+ );
+ } catch {
+ toast.error(
+ billingT(($) => $.workspace.seats.members_over_capacity_title),
+ );
+ }
+ return true;
+ }
+ if (capacityFailure === "full") {
+ try {
+ const preview = await previewSeatPurchase.mutateAsync({
+ additionalSeats: 1,
+ });
+ if (!isSingleSeatInvitePreview(preview)) {
+ toast.error(
+ billingT(($) => $.workspace.seat_purchase.preview_unreadable),
+ );
+ return true;
+ }
+ // Hand over to the purchase confirmation rather than stacking a
+ // second modal on the invite dialog.
+ setInviteOpen(false);
+ setInviteSeatPurchase({
+ workspaceId: workspace.id,
+ ...request,
+ preview,
+ idempotencyKey: createSeatPurchaseKey(workspace.id),
+ phase: "review",
+ });
+ dispatchedInvitePurchaseKey.current = null;
+ } catch (previewError) {
+ toast.error(
+ errorCode(previewError) === "seat_purchase_in_progress"
+ ? billingT(($) => $.workspace.seat_purchase.in_progress)
+ : billingT(($) => $.workspace.seat_purchase.preview_failed),
+ );
+ }
+ return true;
+ }
+ if (capacityFailure === "unavailable") {
+ toast.error(t(($) => $.members.toast_seat_capacity_unavailable));
+ return true;
+ }
+ if (capacityFailure === "rate_limited") {
+ toast.error(t(($) => $.members.toast_seat_capacity_rate_limited));
+ return true;
+ }
+ return false;
+ };
+
// Resolves true once the invitation is sent. retryLimitRefusals retries a
// member-limit refusal after HELD_INVITE_RETRY_MS: right after an upgrade
// the server may still hold the Free policy it re-read moments before.
const inviteMember = async (
email: string,
role: MemberRole,
- { retryLimitRefusals = 0 }: { retryLimitRefusals?: number } = {},
+ {
+ projectIds,
+ retryLimitRefusals = 0,
+ }: { projectIds?: string[]; retryLimitRefusals?: number } = {},
): Promise<boolean> => {
if (!workspace) return false;
setInviteLoading(true);
try {
for (let attempt = 0; ; attempt++) {
try {
- await sendInvitation(email, role);
+ await sendInvitation(email, role, projectIds);
break;
} catch (retryable) {
if (!isMemberLimitReachedError(retryable) || attempt >= retryLimitRefusals) throw retryable;
@@ -622,90 +807,21 @@ export function MembersTab() {
toast.error(t(($) => $.members.toast_member_limit_reached));
return false;
}
- const code = errorCode(e);
- const capacityFailure = seatInvitationCapacityFailure(code);
- if (code === "seat_capacity_overcommitted") {
- try {
- const summary = await qc.fetchQuery({
- ...workspaceSubscriptionSummaryOptions(wsId),
- staleTime: 0,
- });
- const capacity = summary?.seatCapacity;
- toast.error(
- billingT(($) => $.workspace.seats.members_over_capacity_title),
- capacity
- ? {
- description: billingT(
- ($) => $.workspace.seats.occupancy_over_capacity_description,
- {
- // Cloud refuses on used + reserved, so pending
- // invitations have to appear here: the most common
- // trigger is a first ledger snapshot whose member count
- // alone still fits inside the purchased seats.
- occupied: capacity.used + capacity.reserved,
- purchased: capacity.purchased,
- members: capacity.used,
- reserved: capacity.reserved,
- },
- ),
- }
- : undefined,
- );
- } catch {
- toast.error(
- billingT(($) => $.workspace.seats.members_over_capacity_title),
- );
- }
- return false;
- }
- if (capacityFailure === "full") {
- try {
- const preview = await previewSeatPurchase.mutateAsync({
- additionalSeats: 1,
- });
- if (!isSingleSeatInvitePreview(preview)) {
- toast.error(
- billingT(($) => $.workspace.seat_purchase.preview_unreadable),
- );
- return false;
- }
- // Hand over to the purchase confirmation rather than stacking a
- // second modal on the invite dialog.
- setInviteOpen(false);
- setInviteSeatPurchase({
- workspaceId: workspace.id,
- email,
- role,
- preview,
- idempotencyKey: createSeatPurchaseKey(workspace.id),
- phase: "review",
- });
- dispatchedInvitePurchaseKey.current = null;
- } catch (previewError) {
- toast.error(
- errorCode(previewError) === "seat_purchase_in_progress"
- ? billingT(($) => $.workspace.seat_purchase.in_progress)
- : billingT(($) => $.workspace.seat_purchase.preview_failed),
- );
- }
- return false;
- }
- if (capacityFailure === "unavailable") {
- toast.error(t(($) => $.members.toast_seat_capacity_unavailable));
- return false;
- }
- if (capacityFailure === "rate_limited") {
- toast.error(t(($) => $.members.toast_seat_capacity_rate_limited));
- return false;
- }
- toast.error(e instanceof Error ? e.message : t(($) => $.members.toast_invitation_failed));
+ if (await handleSeatRefusal(e, { email, role, projectIds })) return false;
+ refreshFeaturesOnLockedError(qc, wsId, e);
+ toast.error(
+ paidFeatureError(e, e instanceof Error ? e.message : t(($) => $.members.toast_invitation_failed)),
+ );
return false;
} finally {
setInviteLoading(false);
}
};
- const handleInviteMember = () => inviteMember(inviteEmail.trim(), inviteRole);
+ const handleInviteMember = () =>
+ inviteMember(inviteEmail.trim(), inviteRole, {
+ projectIds: inviteRole === "guest" ? inviteProjects : undefined,
+ });
// Why an invitation could not be sent even after paying, checked before
// the upgrade buys a seat for it. The server re-checks on send.
@@ -841,7 +957,9 @@ export function MembersTab() {
dispatchedInvitePurchaseKey.current = purchase.idempotencyKey;
setInviteSeatPurchase({ ...purchase, phase: "inviting" });
- void sendInvitation(purchase.email, purchase.role)
+ void (purchase.promote
+ ? changeRole(purchase.promote.memberId, purchase.role)
+ : sendInvitation(purchase.email, purchase.role, purchase.projectIds))
.then(() => setInviteSeatPurchase(null))
.catch((error) => {
const code = errorCode(error);
@@ -875,6 +993,7 @@ export function MembersTab() {
seatPurchaseSummary.data,
seatPurchaseSummary.dataUpdatedAt,
sendInvitation,
+ changeRole,
t,
wsId,
]);
@@ -925,20 +1044,71 @@ export function MembersTab() {
});
};
- const handleRoleChange = async (memberId: string, role: MemberRole) => {
- if (!workspace) return;
- setMemberActionId(memberId);
+ const applyRoleChange = async (member: MemberWithUser, role: MemberRole) => {
+ setMemberActionId(member.id);
try {
- await api.updateMember(workspace.id, memberId, { role });
- qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });
- toast.success(t(($) => $.members.toast_role_updated));
+ await changeRole(member.id, role);
} catch (e) {
+ const promoting = member.role === "guest";
+ if (promoting && isMemberLimitReachedError(e)) {
+ // A member takes a slot on a plan that caps them; a guest does not.
+ void qc.invalidateQueries({ queryKey: memberLimitKeys.all(wsId) });
+ toast.error(t(($) => $.members.toast_member_limit_reached));
+ return;
+ }
+ if (
+ promoting &&
+ (await handleSeatRefusal(e, {
+ email: member.email,
+ role,
+ promote: { memberId: member.id, name: member.name },
+ }))
+ ) {
+ return;
+ }
toast.error(e instanceof Error ? e.message : t(($) => $.members.toast_role_failed));
} finally {
setMemberActionId(null);
}
};
+ const handleRoleChange = (member: MemberWithUser, role: MemberRole) => {
+ if (!workspace) return;
+ if (role === "guest") {
+ // A guest needs projects to see, so demotion goes through the picker.
+ setProjectsDialog({ member, mode: "demote" });
+ return;
+ }
+ if (member.role === "guest") {
+ setConfirmAction({
+ title: t(($) => $.members.make_member_title, { name: member.name }),
+ description: t(($) => $.members.make_member_description, { name: member.name }),
+ actionLabel: role === "member" ? t(($) => $.members.make_member) : roleConfig[role].label,
+ onConfirm: () => applyRoleChange(member, role),
+ });
+ return;
+ }
+ void applyRoleChange(member, role);
+ };
+
+ const handleProjectsConfirm = async (projectIds: string[]) => {
+ if (!workspace || !projectsDialog) return;
+ const { member, mode } = projectsDialog;
+ try {
+ if (mode === "demote") {
+ await changeRole(member.id, "guest", projectIds);
+ } else {
+ await api.setMemberProjects(workspace.id, member.id, projectIds);
+ await qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });
+ toast.success(t(($) => $.members.toast_projects_updated));
+ }
+ setProjectsDialog(null);
+ } catch (e) {
+ refreshFeaturesOnLockedError(qc, wsId, e);
+ toast.error(paidFeatureError(e, e instanceof Error ? e.message : t(($) => $.members.toast_role_failed)));
+ }
+ };
+
const handleRemoveMember = (member: MemberWithUser) => {
if (!workspace) return;
setConfirmAction({
@@ -1025,14 +1195,31 @@ export function MembersTab() {
{ value: "720", label: t(($) => $.members.expiry_30d) },
{ value: "0", label: t(($) => $.members.expiry_never) },
];
+ const inviteRoles: MemberRole[] = guestsEnabled ? ["member", "admin", "guest"] : ["member", "admin"];
+ const guestInviteLocked = inviteRole === "guest" && !canAddGuests;
const views: { value: MembersView; label: string; count: number }[] = [
- { value: "members", label: t(($) => $.members.members_label), count: members.length },
+ {
+ value: "members",
+ label: showGuestViews ? t(($) => $.members.all_label) : t(($) => $.members.members_label),
+ count: members.length,
+ },
+ ...(showGuestViews
+ ? [
+ {
+ value: "seated" as const,
+ label: t(($) => $.members.members_label),
+ count: members.length - guestCount,
+ },
+ { value: "guests" as const, label: t(($) => $.members.guests_label), count: guestCount },
+ ]
+ : []),
{ value: "invitations", label: t(($) => $.members.pending_label), count: invitations.length },
...(canManageWorkspace
? [{ value: "links" as const, label: t(($) => $.members.share_links_label), count: shareLinks.length }]
: []),
];
const activeView = views.some((item) => item.value === view) ? view : "members";
+ const isPeopleView = activeView === "members" || activeView === "seated" || activeView === "guests";
return (
<SettingsTab
@@ -1074,6 +1261,12 @@ export function MembersTab() {
purchased: seats.purchased,
})}
{" · "}
+ {guestCount > 0 ? (
+ <>
+ {t(($) => $.members.guest_count, { count: guestCount })}
+ {" · "}
+ </>
+ ) : null}
<AppLink
href={
navigation
@@ -1085,8 +1278,12 @@ export function MembersTab() {
{t(($) => $.members.manage_seats)}
</AppLink>
</span>
+ ) : guestCount > 0 ? (
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.members.guest_count, { count: guestCount })}
+ </span>
) : null}
- {activeView === "members" ? (
+ {isPeopleView ? (
<div className="relative w-full sm:w-56">
<Search
aria-hidden="true"
@@ -1110,7 +1307,7 @@ export function MembersTab() {
</div>
</div>
- {activeView === "members" ? (
+ {isPeopleView ? (
visibleMembers.length > 0 ? (
<SettingsCard>
{visibleMembers.map((m) => (
@@ -1119,10 +1316,13 @@ export function MembersTab() {
member={m}
canManage={canManageWorkspace}
canManageOwners={isOwner}
+ guestsEnabled={canAddGuests}
+ projectNames={(m.project_ids ?? []).flatMap((id) => projectTitles.get(id) ?? [])}
ownerCount={ownerCount}
isSelf={m.user_id === user?.id}
busy={memberActionId === m.id}
- onRoleChange={(role) => handleRoleChange(m.id, role)}
+ onRoleChange={(role) => handleRoleChange(m, role)}
+ onManageProjects={() => setProjectsDialog({ member: m, mode: "edit" })}
onRemove={() => handleRemoveMember(m)}
/>
</div>
@@ -1183,9 +1383,9 @@ export function MembersTab() {
className="space-y-4"
onSubmit={(event) => {
event.preventDefault();
- if (!inviteEmail.trim()) return;
- if (canUpgradeForInvite) handleUpgradeAndInvite();
- else if (!inviteBlockedByMemberLimit) void handleInviteMember();
+ if (!inviteEmail.trim() || guestInviteMissingProjects || guestInviteLocked) return;
+ if (inviteCanUpgrade) handleUpgradeAndInvite();
+ else if (!inviteFull) void handleInviteMember();
}}
>
<div className="space-y-1.5">
@@ -1202,31 +1402,57 @@ export function MembersTab() {
autoFocus
/>
</div>
- <div className="space-y-1.5">
- <Label htmlFor="invite-role">{t(($) => $.members.role_label)}</Label>
- <Select
- items={roleItems}
- value={inviteRole}
- onValueChange={(value) => setInviteRole(value as MemberRole)}
- >
- <SelectTrigger id="invite-role" className="w-full">
- <SelectValue>{() => roleConfig[inviteRole].label}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {roleItems.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- <span className="flex flex-col">
- <span>{item.label}</span>
- <span className="text-caption text-muted-foreground">
- {roleConfig[item.value].description}
- </span>
+ <fieldset className="space-y-1.5">
+ <legend className="mb-1.5 text-body leading-none font-medium">
+ {t(($) => $.members.role_label)}
+ </legend>
+ <div className="space-y-2">
+ {inviteRoles.map((role) => (
+ <label
+ key={role}
+ className={cn(
+ "flex cursor-pointer items-start gap-3 rounded-lg border px-3 py-2.5 transition-colors",
+ inviteRole === role
+ ? "border-foreground"
+ : "border-border hover:bg-surface-hover",
+ )}
+ >
+ <input
+ type="radio"
+ name="invite-role"
+ value={role}
+ checked={inviteRole === role}
+ onChange={() => setInviteRole(role)}
+ className="mt-0.5 size-3.5 shrink-0 accent-foreground"
+ />
+ <span className="min-w-0">
+ <span className="flex items-center gap-2 text-body font-medium">
+ {roleConfig[role].label}
+ {role === "guest" ? (
+ <Badge variant="secondary" className="bg-success/10 text-success">
+ {t(($) => $.members.guest_free_tag)}
+ </Badge>
+ ) : null}
</span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- {inviteBlockedByMemberLimit && enforcedMemberLimit ? (
+ <span className="block text-caption text-muted-foreground">
+ {roleConfig[role].description}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ {inviteRole === "guest" && guestAccess.state === "unavailable" ? (
+ <PaidFeatureNotice state="unavailable" />
+ ) : inviteRole === "guest" ? (
+ <GuestProjectsField
+ id="invite-guest-projects"
+ projects={shareableProjects}
+ value={inviteProjects}
+ onChange={setInviteProjects}
+ />
+ ) : null}
+ {inviteFull && enforcedMemberLimit ? (
<Alert>
<Users aria-hidden="true" />
<AlertTitle>
@@ -1263,7 +1489,7 @@ export function MembersTab() {
>
{t(($) => $.members.confirm_cancel)}
</Button>
- {subscriptionNeedsAttention ? (
+ {inviteNeedsAttention ? (
<Button
type="button"
disabled={!navigation}
@@ -1275,7 +1501,7 @@ export function MembersTab() {
>
{t(($) => $.members.open_billing)}
</Button>
- ) : canUpgradeForInvite ? (
+ ) : inviteCanUpgrade ? (
<Button
type="button"
disabled={inviteLoading || !inviteEmail.trim() || !navigation || !inviteChecksReady}
@@ -1286,10 +1512,20 @@ export function MembersTab() {
) : (
<Button
type="submit"
- disabled={inviteLoading || !inviteEmail.trim() || inviteBlockedByMemberLimit}
+ disabled={
+ inviteLoading ||
+ !inviteEmail.trim() ||
+ inviteFull ||
+ guestInviteMissingProjects ||
+ guestInviteLocked
+ }
aria-busy={inviteLoading || undefined}
>
- {inviteLoading ? t(($) => $.members.inviting) : t(($) => $.members.invite_button)}
+ {inviteLoading
+ ? t(($) => $.members.inviting)
+ : inviteRole === "guest"
+ ? t(($) => $.members.invite_guest_button)
+ : t(($) => $.members.invite_button)}
</Button>
)}
</div>
@@ -1390,13 +1626,19 @@ export function MembersTab() {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
- {t(($) => $.members.seat_purchase_title)}
+ {inviteSeatPurchase?.promote
+ ? t(($) => $.members.make_member_title, { name: inviteSeatPurchase.promote.name })
+ : t(($) => $.members.seat_purchase_title)}
</AlertDialogTitle>
<AlertDialogDescription>
{inviteSeatPurchase?.phase === "review"
- ? t(($) => $.members.seat_purchase_description, {
- email: inviteSeatPurchase.email,
- })
+ ? inviteSeatPurchase.promote
+ ? t(($) => $.members.make_member_seat_description, {
+ name: inviteSeatPurchase.promote.name,
+ })
+ : t(($) => $.members.seat_purchase_description, {
+ email: inviteSeatPurchase.email,
+ })
: inviteSeatPurchase?.phase === "error"
? inviteSeatPurchase.error
: t(($) => $.members.seat_purchase_waiting)}
@@ -1451,7 +1693,9 @@ export function MembersTab() {
<div className="flex items-center gap-2 text-body text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{inviteSeatPurchase.phase === "inviting"
- ? t(($) => $.members.inviting)
+ ? inviteSeatPurchase.promote
+ ? t(($) => $.members.making_member)
+ : t(($) => $.members.inviting)
: t(($) => $.members.seat_purchase_waiting)}
</div>
)}
@@ -1470,7 +1714,9 @@ export function MembersTab() {
void handlePurchaseSeatAndInvite();
}}
>
- {t(($) => $.members.purchase_seat_and_invite)}
+ {inviteSeatPurchase.promote
+ ? t(($) => $.members.purchase_seat_and_make_member)
+ : t(($) => $.members.purchase_seat_and_invite)}
</AlertDialogAction>
)}
{inviteSeatPurchase?.phase === "error" &&
@@ -1488,6 +1734,31 @@ export function MembersTab() {
</AlertDialogContent>
</AlertDialog>
+ <GuestProjectsDialog
+ open={projectsDialog !== null}
+ title={
+ projectsDialog?.mode === "demote"
+ ? t(($) => $.members.make_guest_title, { name: projectsDialog.member.name })
+ : t(($) => $.members.manage_projects_title, { name: projectsDialog?.member.name ?? "" })
+ }
+ description={
+ projectsDialog?.mode === "demote"
+ ? t(($) => $.members.make_guest_description, { name: projectsDialog.member.name })
+ : undefined
+ }
+ confirmLabel={
+ projectsDialog?.mode === "demote"
+ ? t(($) => $.members.make_guest_button)
+ : t(($) => $.members.save_projects)
+ }
+ projects={shareableProjects}
+ initial={projectsDialog?.member.project_ids ?? []}
+ onOpenChange={(open) => {
+ if (!open) setProjectsDialog(null);
+ }}
+ onConfirm={handleProjectsConfirm}
+ />
+
<AlertDialog open={!!confirmAction} onOpenChange={(v) => { if (!v) setConfirmAction(null); }}>
<AlertDialogContent>
<AlertDialogHeader>
@@ -1503,7 +1774,7 @@ export function MembersTab() {
setConfirmAction(null);
}}
>
- {t(($) => $.members.confirm_action)}
+ {confirmAction?.actionLabel ?? t(($) => $.members.confirm_action)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 608fe68432..8686acd062 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -131,6 +131,8 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
const workspaceName = workspace?.name ?? t(($) => $.page.workspace_fallback);
const { role } = useCurrentMember(workspace?.id ?? "");
const isMember = role === "member";
+ // A guest (MUL-9420) has personal settings only.
+ const isGuest = role === "guest";
const navigation = useNavigation();
const paths = useWorkspacePaths();
const listCollapsed = useListColumnCollapsed();
@@ -149,7 +151,7 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
options: { wide?: boolean; adminOnly?: boolean } = {},
): SettingsEntry => ({ value, label, icon, content, ...options });
- const groups: SettingsScopeGroup[] = [
+ const scopeGroups: SettingsScopeGroup[] = [
{
key: "personal",
label: t(($) => $.page.groups.personal),
@@ -282,6 +284,9 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
]
: []),
];
+ const groups = isGuest
+ ? scopeGroups.filter((group) => group.key !== "workspace")
+ : scopeGroups;
const allEntries = groups.flatMap((group) =>
group.subgroups.flatMap((subgroup) => subgroup.entries),
);
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index e05f835436..347fe454e2 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -154,6 +154,7 @@ var concurrentIndexCleanups = map[string]string{
"694_doc_version_workspace_idx": "doc_version_workspace_idx",
"696_inbox_item_active_shown_idx": "idx_inbox_active_shown",
"698_autopilot_run_idempotency_key_idx": "uq_autopilot_run_idempotency_key",
+ "701_member_search_access_pkey_index": "member_search_access_pkey_idx",
"671_weixin_account_state_unique_index": "weixin_account_state_pkey",
"669_weixin_login_session_unique_index": "weixin_login_session_pkey",
"666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 654b51429e..6daf193afb 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -43,6 +43,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/weixin"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/realtime"
"github.com/multica-ai/multica/server/internal/seatcapacity"
"github.com/multica-ai/multica/server/internal/service"
@@ -1886,6 +1887,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/members/{memberId}", func(r chi.Router) {
r.Patch("/", h.UpdateMember)
r.Delete("/", h.DeleteMember)
+ r.Put("/projects", h.SetMemberProjects)
})
r.Delete("/invitations/{invitationId}", h.RevokeInvitation)
// Curating the shared MCP library is an admin action.
@@ -2863,15 +2865,20 @@ type membershipChecker struct {
queries *db.Queries
}
+// IsMember answers for realtime, which guests (MUL-9420) do not get: see
+// GetRealtimeMemberships.
func (mc *membershipChecker) IsMember(ctx context.Context, userID, workspaceID string) (bool, error) {
- _, err := mc.queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ member, err := mc.queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
UserID: parseUUID(userID),
WorkspaceID: parseUUID(workspaceID),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
- return err == nil, err
+ if err != nil {
+ return false, err
+ }
+ return !projectaccess.IsGuestRole(member.Role), nil
}
func (mc *membershipChecker) Members(ctx context.Context, identities []realtime.MembershipIdentity) (map[realtime.MembershipIdentity]bool, error) {
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
index 289aeca5e4..df6331c796 100644
--- a/server/internal/entitlement/README.md
+++ b/server/internal/entitlement/README.md
@@ -194,6 +194,7 @@ permission checks, so a caller refused by those gets the ordinary error.
| Feature | Restricted additions | Always allowed |
| --- | --- | --- |
| `private_projects` | create a private project; make a project private; add someone who is not a member yet, directly or by making them the lead | remove members; make it workspace-visible; delete or archive; set the lead to an existing member, an agent or nobody; other fields; the owner's recovery join |
+| `guests` | invite a guest; make a member a guest; share another project with a guest | remove a guest; narrow a guest's projects; make a guest a member; accept an invitation sent while the plan included guests |
A stale cached `enforce` is downgraded to `observe` with reason `stale` and
`Downgraded` set, then to `off`, exactly like gates, so a Cloud outage admits additions rather than
diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.go
index ede57b0dfd..bfda091170 100644
--- a/server/internal/entitlement/types.go
+++ b/server/internal/entitlement/types.go
@@ -113,16 +113,19 @@ type FeatureName string
const (
FeaturePrivateProjects FeatureName = "private_projects"
+ // FeatureGuests covers adding guests (MUL-9420): inviting one, making a
+ // member a guest, and sharing more projects with a guest.
+ FeatureGuests FeatureName = "guests"
)
// Features lists every paid feature this consumer understands.
func Features() []FeatureName {
- return []FeatureName{FeaturePrivateProjects}
+ return []FeatureName{FeaturePrivateProjects, FeatureGuests}
}
func (n FeatureName) Valid() bool {
switch n {
- case FeaturePrivateProjects:
+ case FeaturePrivateProjects, FeatureGuests:
return true
default:
return false
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index a8e164d63e..e282b61768 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -42,6 +42,13 @@ const (
// for a deployment. It is a GLOBAL switch. Turning it off leaves existing
// doc rows untouched — they simply become unreachable until it is back on.
DocsV1 = "docs_v1"
+ // WorkspaceGuests gates inviting guests and turning members into guests
+ // (MUL-9420). On by default, so self-hosted servers have guests. A server
+ // that predates guests treats a guest row as a full member, so a rolling
+ // deploy should run with FF_WORKSPACE_GUESTS=off until every replica
+ // serves this version. Existing guests keep their narrowed access either
+ // way.
+ WorkspaceGuests = "workspace_guests"
// agentBuilderCompat is no longer a release flag. Keep publishing the key
// as enabled so installed desktop clients that still gate the AI creation
// entry on this config decision receive the permanently enabled behavior.
@@ -93,11 +100,16 @@ func DocsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, DocsV1, false)
}
+func WorkspaceGuestsEnabled(ctx context.Context, flags *featureflag.Service) bool {
+ return flags.IsEnabled(ctx, WorkspaceGuests, true)
+}
+
func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {
- out := make(map[string]bool, len(frontendPublicFlags)+4)
+ out := make(map[string]bool, len(frontendPublicFlags)+5)
for _, key := range frontendPublicFlags {
out[key] = flags.IsEnabled(ctx, key, false)
}
+ out[WorkspaceGuests] = WorkspaceGuestsEnabled(ctx, flags)
out[agentBuilderCompat] = true
out[agentSkillTogglesCompat] = true
out[resourceLabelsCompat] = true
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index d7aae520cb..da0850cb76 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -24,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/runtimeapps"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
@@ -1221,6 +1222,23 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to list agents")
return
}
+ if projectaccess.IsGuestRole(member.Role) {
+ // Not the agent directory: only the agents the guest meets in its
+ // projects, with just enough to render their names.
+ seen, err := h.guestAgentIDs(r.Context(), member)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agents")
+ return
+ }
+ names := make([]AgentResponse, 0, len(seen))
+ for _, a := range agents {
+ if seen[a.ID.Bytes] {
+ names = append(names, guestAgentView(h.agentToResponse(a)))
+ }
+ }
+ writeJSON(w, http.StatusOK, names)
+ return
+ }
runtimeAvailabilityByID, err := h.loadAgentRuntimeAvailability(r.Context(), agents, workspaceID, userID, member.Role, time.Now())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to load agent runtime availability")
diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.go
index 62470b5ace..9d29d50f93 100644
--- a/server/internal/handler/agent_access.go
+++ b/server/internal/handler/agent_access.go
@@ -6,6 +6,7 @@ import (
"net/http"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -78,6 +79,18 @@ func (h *Handler) invokeAgentDecision(ctx context.Context, agent db.Agent, actor
effectiveUser = originatorUserID
}
+ isWorkspaceMember := false
+ if effectiveUser != "" {
+ if m, err := h.getWorkspaceMember(ctx, effectiveUser, workspaceID); err == nil {
+ // Guests never run agents (MUL-9420), not even one they owned
+ // before becoming a guest.
+ if projectaccess.IsGuestRole(m.Role) {
+ return false
+ }
+ isWorkspaceMember = true
+ }
+ }
+
// The agent owner may always invoke their own agent.
if effectiveUser != "" && uuidToString(agent.OwnerID) == effectiveUser {
return true
@@ -105,12 +118,6 @@ func (h *Handler) invokeAgentDecision(ctx context.Context, agent db.Agent, actor
// member-/team-scoped private-ish allow-list and can never smuggle itself
// onto someone's specific-people grant.
workspaceBroad := actorType == "agent" || actorType == "system"
- isWorkspaceMember := false
- if effectiveUser != "" {
- if _, err := h.getWorkspaceMember(ctx, effectiveUser, workspaceID); err == nil {
- isWorkspaceMember = true
- }
- }
for _, t := range targets {
switch t.TargetType {
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 150864fa87..70fd62b7c5 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1733,6 +1733,9 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
// Determine author identity: agent (via X-Agent-ID header) or member.
authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
+ if h.refuseGuestMention(w, r, uuidToString(issue.WorkspaceID), userID, authorType, req.Content) {
+ return
+ }
// A running turn receives text only, so a comment that carries files is
// always a normal trigger. A member's explicit skill selection is the
@@ -1887,6 +1890,8 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
unboundIDs, err = qtx.LockUnboundAttachmentsForCommentLink(r.Context(), db.LockUnboundAttachmentsForCommentLinkParams{
WorkspaceID: issue.WorkspaceID,
AttachmentIds: attachmentIDs,
+ UploaderType: authorType,
+ UploaderID: parseUUID(authorID),
})
if err == nil {
created, err = qtx.CreateComment(r.Context(), createParams)
@@ -1905,6 +1910,8 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
IssueID: issue.ID,
WorkspaceID: issue.WorkspaceID,
AttachmentIds: attachmentIDs,
+ UploaderType: authorType,
+ UploaderID: parseUUID(authorID),
})
}
if err == nil {
@@ -3475,6 +3482,11 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "content is required")
return
}
+ // The same mention rule as CreateComment: an edit must not add what a
+ // new comment could not carry.
+ if h.refuseGuestMention(w, r, workspaceID, userID, actorType, req.Content) {
+ return
+ }
if req.ExpectedRevision != nil {
if *req.ExpectedRevision < 1 {
writeError(w, http.StatusBadRequest, "expected_revision must be a positive integer")
@@ -3511,6 +3523,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
sourceTaskID := existing.SourceTaskID
var triggerIssue *db.Issue
var cancelled []db.AgentTaskQueue
+ cancelInEditTx := strictContentEdit || replaceAttachments
if oldContent != req.Content {
issue, err := h.Queries.GetIssue(r.Context(), existing.IssueID)
if err != nil {
@@ -3535,9 +3548,11 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
sourceTaskID = pgtype.UUID{}
}
// Legacy clients keep the existing cancel-before-update behavior. Strict
- // revision writes defer cancellation until the conditional UPDATE wins,
- // so a race that returns 409 cannot mutate the task queue.
- if !strictContentEdit {
+ // revision writes, and any edit that sets attachments, cancel inside
+ // the edit's transaction once everything else has succeeded, so a 409
+ // (a lost revision race, an attachment no longer available) leaves the
+ // task queue untouched.
+ if !cancelInEditTx {
cancelled, err = h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID)
if err != nil {
slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
@@ -3576,17 +3591,33 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ // Unbound drafts this edit may adopt are locked before UpdateComment
+ // takes the issue, the order CreateComment uses. The reverse order
+ // deadlocks against a comment created with the same draft.
+ if replaceAttachments && len(attachmentIDs) > 0 {
+ _, err = qtx.LockUnboundAttachmentsForCommentLink(r.Context(), db.LockUnboundAttachmentsForCommentLinkParams{
+ WorkspaceID: existing.WorkspaceID,
+ AttachmentIds: attachmentIDs,
+ UploaderType: actorType,
+ UploaderID: parseUUID(actorID),
+ })
+ }
var updated db.UpdateCommentRow
- updated, err = qtx.UpdateComment(r.Context(), updateParams)
+ if err == nil {
+ updated, err = qtx.UpdateComment(r.Context(), updateParams)
+ }
if err == nil {
comment = updated.Comment()
issueRevision = updated.IssueRevision
}
- if err == nil && oldContent != req.Content && strictContentEdit {
- cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)
- if err == nil {
- err = service.SettleTerminalTaskState(r.Context(), qtx, cancelled...)
- }
+ if err == nil && replaceAttachments && len(attachmentIDs) > 0 {
+ _, err = qtx.BindUploaderDraftAttachmentsToIssue(r.Context(), db.BindUploaderDraftAttachmentsToIssueParams{
+ IssueID: existing.IssueID,
+ WorkspaceID: existing.WorkspaceID,
+ AttachmentIds: attachmentIDs,
+ UploaderType: actorType,
+ UploaderID: parseUUID(actorID),
+ })
}
if err == nil && replaceAttachments {
var changed int64
@@ -3595,6 +3626,23 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
IssueID: existing.IssueID,
AttachmentIds: attachmentIDs,
})
+ // Every requested file must have ended up on the comment. One a
+ // concurrent request took first (a comment published with the
+ // same draft) refuses the whole edit instead of saving the text
+ // without it.
+ if err == nil && len(attachmentIDs) > 0 {
+ var got []pgtype.UUID
+ got, err = qtx.ListCommentAttachmentIDsAmong(r.Context(), db.ListCommentAttachmentIDsAmongParams{
+ CommentID: comment.ID,
+ WorkspaceID: existing.WorkspaceID,
+ AttachmentIds: attachmentIDs,
+ })
+ if err == nil {
+ if missing := firstMissingID(attachmentIDs, got); missing.Valid {
+ err = commentAttachmentUnavailableError{id: missing}
+ }
+ }
+ }
if err == nil && changed > 0 && oldContent == req.Content {
comment, err = qtx.BumpCommentRevision(r.Context(), db.BumpCommentRevisionParams{
ID: comment.ID,
@@ -3602,9 +3650,24 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
})
}
}
+ // Last, after the attachments checked out: the runs built from the old
+ // body are cancelled in the same transaction, so any failure above
+ // rolls back with them still queued.
+ if err == nil && oldContent != req.Content {
+ cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)
+ if err == nil {
+ err = service.SettleTerminalTaskState(r.Context(), qtx, cancelled...)
+ }
+ }
if err == nil {
err = tx.Commit(r.Context())
}
+ if err != nil {
+ // Release the issue and comment locks before the error handling
+ // below reads them on other connections.
+ _ = tx.Rollback(r.Context())
+ cancelled = nil
+ }
if err == nil {
h.TaskService.BroadcastCancelledTasks(r.Context(), uuidToString(existing.WorkspaceID), cancelled)
}
@@ -3620,11 +3683,16 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
if err != nil {
slog.Warn("update comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
- if triggerIssue != nil && !strictContentEdit {
+ if triggerIssue != nil && !cancelInEditTx {
// Cancellation committed but the edit did not. Restore the complete
// original batch, including the still-valid unchanged comment.
h.retriggerCancelledTaskSurvivors(r.Context(), *triggerIssue, cancelled, pgtype.UUID{})
}
+ var unavailable commentAttachmentUnavailableError
+ if errors.As(err, &unavailable) {
+ writeError(w, http.StatusConflict, "attachment "+uuidToString(unavailable.id)+" is no longer available")
+ return
+ }
if errors.Is(err, pgx.ErrNoRows) {
current, reloadErr := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{ID: commentUUID, WorkspaceID: wsUUID})
if errors.Is(reloadErr, pgx.ErrNoRows) || (reloadErr == nil && current.DeletedAt.Valid) {
@@ -3823,6 +3891,28 @@ type commentDeletion struct {
// lockCommentAttachments validates and pins the full requested set, including
// existing issue attachments. The caller must already hold the issue's row
// lock and have locked ownerless uploads before it; see CreateComment.
+// commentAttachmentUnavailableError reports a requested attachment that a
+// comment edit could not take, so the edit is rolled back.
+type commentAttachmentUnavailableError struct{ id pgtype.UUID }
+
+func (e commentAttachmentUnavailableError) Error() string {
+ return "attachment " + uuidToString(e.id) + " is no longer available"
+}
+
+// firstMissingID returns the first id in want that is not in have.
+func firstMissingID(want, have []pgtype.UUID) pgtype.UUID {
+ seen := make(map[pgtype.UUID]struct{}, len(have))
+ for _, id := range have {
+ seen[id] = struct{}{}
+ }
+ for _, id := range want {
+ if _, ok := seen[id]; !ok {
+ return id
+ }
+ }
+ return pgtype.UUID{}
+}
+
func lockCommentAttachments(ctx context.Context, qtx *db.Queries, workspaceID, issueID pgtype.UUID, ids, unboundIDs []pgtype.UUID) (missing pgtype.UUID, err error) {
locked, err := qtx.LockAttachmentsForCommentLink(ctx, db.LockAttachmentsForCommentLinkParams{
WorkspaceID: workspaceID,
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 8e378bf5d1..c07a8426c9 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -6325,6 +6325,15 @@ func (h *Handler) GetActiveTaskForIssue(w http.ResponseWriter, r *http.Request)
for i, t := range tasks {
resp[i] = taskToResponse(t, workspaceID)
}
+ // A guest (MUL-9420) learns only that an agent is working on the issue,
+ // not where or on what instructions.
+ if h.isGuest(r, workspaceID, requestUserID(r)) {
+ for i := range resp {
+ resp[i] = guestTaskView(resp[i])
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"tasks": resp})
+ return
+ }
// Same issue-facing attribution surface as ListTasksByIssue — hydrate names.
h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 1866c32841..e3be64b024 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -501,7 +501,14 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
if !h.requireProjectVisible(w, r, workspaceID, issue.ProjectID, http.StatusForbidden, "invalid issue_id") {
return
}
- params.IssueID = issue.ID
+ // A guest's upload (MUL-9420) is a draft for its next comment, not
+ // a change to the issue: it stays unbound, visible only to the
+ // guest, until CreateComment links it with the comment
+ // (LinkAttachmentsToComment accepts unbound rows). A member's
+ // upload still attaches to the issue at once.
+ if uploaderType != "member" || !h.isGuest(r, workspaceID, userID) {
+ params.IssueID = issue.ID
+ }
}
if commentID := r.FormValue("comment_id"); commentID != "" {
commentUUID, ok := parseUUIDOrBadRequest(w, commentID, "comment_id")
@@ -517,6 +524,13 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
if !h.requireIssueIDVisible(w, r, workspaceID, comment.IssueID, http.StatusForbidden, "invalid comment_id") {
return
}
+ // A guest attaches files only to its own comments (MUL-9420);
+ // seeing a comment is not enough to add to it.
+ if uploaderType == "member" && h.isGuest(r, workspaceID, userID) &&
+ (comment.AuthorType != "member" || uuidToString(comment.AuthorID) != userID) {
+ writeError(w, http.StatusForbidden, "invalid comment_id")
+ return
+ }
params.CommentID = comment.ID
}
if chatSessionID := r.FormValue("chat_session_id"); chatSessionID != "" {
diff --git a/server/internal/handler/guest.go b/server/internal/handler/guest.go
new file mode 100644
index 0000000000..8922f326fe
--- /dev/null
+++ b/server/internal/handler/guest.go
@@ -0,0 +1,493 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/seatcapacity"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// maxGuestProjects bounds one request; a guest with more projects than this
+// is better served as a member.
+const maxGuestProjects = 100
+
+// guestsEnabled writes a 403 when new guests are switched off.
+func (h *Handler) guestsEnabled(w http.ResponseWriter, r *http.Request) bool {
+ if featureflags.WorkspaceGuestsEnabled(r.Context(), h.FeatureFlags) {
+ return true
+ }
+ writeFeatureDisabled(w, "workspace_guests_disabled", "guests are not enabled")
+ return false
+}
+
+// requireGuestAddition admits a write that adds a guest or widens one:
+// guests must be switched on for this deployment (the rollout flag) and
+// included in the workspace's plan (the guests paid feature). Removing a
+// guest, narrowing its projects and promoting it are never restricted, and
+// existing guests keep their access after a downgrade.
+func (h *Handler) requireGuestAddition(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, operation string) (featureAdmission, bool) {
+ if !h.guestsEnabled(w, r) {
+ return featureAdmission{}, false
+ }
+ return h.requireFeatureAddition(w, r, workspaceID, entitlement.FeatureGuests, operation)
+}
+
+// isGuest reports whether userID is a guest of the workspace. A failed lookup
+// reads as not a guest: callers use it for a clearer error, while access
+// itself is enforced by projectaccess and the agent invocation gate.
+func (h *Handler) isGuest(r *http.Request, workspaceID, userID string) bool {
+ if m, ok := ctxMember(r.Context()); ok && uuidToString(m.WorkspaceID) == workspaceID && uuidToString(m.UserID) == userID {
+ return projectaccess.IsGuestRole(m.Role)
+ }
+ m, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)
+ return err == nil && projectaccess.IsGuestRole(m.Role)
+}
+
+// guestMentionForbidden reports whether content carries a mention a guest may
+// not write: an agent or a squad, which would ask an agent to run, or @all,
+// which would notify the whole workspace. Creating and editing a comment
+// apply the same rule.
+func guestMentionForbidden(content string) bool {
+ for _, m := range util.ParseMentions(content) {
+ if m.Type == "agent" || m.Type == "squad" || m.IsMentionAll() {
+ return true
+ }
+ }
+ return false
+}
+
+const guestMentionForbiddenMessage = "guests cannot mention agents, squads or everyone"
+
+// refuseGuestMention writes a 403 when a guest member writes a comment with a
+// mention guestMentionForbidden rejects.
+func (h *Handler) refuseGuestMention(w http.ResponseWriter, r *http.Request, workspaceID, userID, actorType, content string) bool {
+ if actorType != "member" || !h.isGuest(r, workspaceID, userID) || !guestMentionForbidden(content) {
+ return false
+ }
+ writeError(w, http.StatusForbidden, guestMentionForbiddenMessage)
+ return true
+}
+
+// guestTaskView is all of a run a guest is shown: that an agent is working on
+// the issue and since when, without its working directory, handoff, trigger
+// or result.
+func guestTaskView(full AgentTaskResponse) AgentTaskResponse {
+ view := restrictedTaskResponse(full)
+ view.IssueID = full.IssueID
+ return view
+}
+
+// guestAgentIDs is the set of agents a guest meets in its projects.
+func (h *Handler) guestAgentIDs(ctx context.Context, member db.Member) (map[[16]byte]bool, error) {
+ ids, err := h.Queries.ListAgentIDsSeenByGuest(ctx, db.ListAgentIDsSeenByGuestParams{
+ WorkspaceID: member.WorkspaceID, UserID: member.UserID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ seen := make(map[[16]byte]bool, len(ids))
+ for _, id := range ids {
+ if id.Valid {
+ seen[id.Bytes] = true
+ }
+ }
+ return seen, nil
+}
+
+// requireGuestProjectAddition admits adding userIDs to a project when that
+// shares the project with a guest who is not a member of it yet: guests must
+// be switched on and in the plan, as for every other guest addition. projectID
+// is invalid for a project being created. Adding only members, or guests
+// already in the project, is never restricted here.
+func (h *Handler) requireGuestProjectAddition(w http.ResponseWriter, r *http.Request, workspaceID, projectID pgtype.UUID, userIDs []pgtype.UUID) (featureAdmission, bool) {
+ if len(userIDs) == 0 {
+ return featureAdmission{}, true
+ }
+ if !projectID.Valid {
+ projectID = projectaccess.NoProject
+ }
+ n, err := h.Queries.CountGuestsNotInProject(r.Context(), db.CountGuestsNotInProjectParams{
+ WorkspaceID: workspaceID, UserIds: userIDs, ProjectID: projectID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check project members")
+ return featureAdmission{}, false
+ }
+ if n == 0 {
+ return featureAdmission{}, true
+ }
+ return h.requireGuestAddition(w, r, workspaceID, "add_projects")
+}
+
+// errMemberRoleChanged reports that a member's role changed between the read
+// a role change was decided on and the transaction that applies it.
+var errMemberRoleChanged = errors.New("member role changed")
+
+func writeMemberRoleChanged(w http.ResponseWriter) {
+ writeJSON(w, http.StatusConflict, map[string]string{
+ "error": "the member's role changed while this request was in flight; reload and try again",
+ "code": "member_role_changed",
+ })
+}
+
+// lockMemberRole locks the member row in the transaction and checks it still
+// has the role the change was decided on. Concurrent changes to one member
+// then apply in turn, and a request decided on a stale role is refused
+// instead of skipping the checks the current role needs (a guest becoming a
+// member takes a seat; a member becoming a guest gives up its access).
+func lockMemberRole(ctx context.Context, q *db.Queries, memberID pgtype.UUID, expectedRole string) (db.Member, error) {
+ m, err := q.GetMemberForUpdate(ctx, memberID)
+ if err != nil {
+ return db.Member{}, err
+ }
+ if m.Role != expectedRole {
+ return db.Member{}, errMemberRoleChanged
+ }
+ return m, nil
+}
+
+// writeMemberUpdateError maps a role-change failure to its response.
+func writeMemberUpdateError(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, errMemberRoleChanged):
+ writeMemberRoleChanged(w)
+ case errors.Is(err, pgx.ErrNoRows):
+ writeError(w, http.StatusNotFound, "member not found")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to update member")
+ }
+}
+
+// guestAgentView is all of an agent a guest is shown: enough to render its
+// name and avatar on the comments it wrote.
+func guestAgentView(a AgentResponse) AgentResponse {
+ return AgentResponse{
+ ID: a.ID,
+ WorkspaceID: a.WorkspaceID,
+ Name: a.Name,
+ AvatarURL: a.AvatarURL,
+ ArchivedAt: a.ArchivedAt,
+ RuntimeConfig: map[string]any{},
+ ConversationStarters: []AgentConversationStarter{},
+ CustomArgs: []string{},
+ InvocationTargets: []AgentInvocationTargetDTO{},
+ Skills: []AgentSkillSummary{},
+ DisabledRuntimeSkills: []DisabledRuntimeSkill{},
+ }
+}
+
+// parseGuestProjectIDs validates the projects a guest may see: at least one,
+// each a project of this workspace.
+func (h *Handler) parseGuestProjectIDs(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, raw []string) ([]pgtype.UUID, bool) {
+ if len(raw) == 0 {
+ writeError(w, http.StatusBadRequest, "a guest needs at least one project")
+ return nil, false
+ }
+ if len(raw) > maxGuestProjects {
+ writeError(w, http.StatusBadRequest, "too many projects")
+ return nil, false
+ }
+ seen := map[[16]byte]bool{}
+ ids := make([]pgtype.UUID, 0, len(raw))
+ for _, s := range raw {
+ id, err := util.ParseUUID(s)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid project id")
+ return nil, false
+ }
+ if seen[id.Bytes] {
+ continue
+ }
+ seen[id.Bytes] = true
+ ids = append(ids, id)
+ }
+ found, err := h.Queries.ListWorkspaceProjectIDs(r.Context(), db.ListWorkspaceProjectIDsParams{
+ WorkspaceID: workspaceID, ProjectIds: ids,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load projects")
+ return nil, false
+ }
+ // The requester can only share a project they can see themselves.
+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(workspaceID))
+ if !ok {
+ return nil, false
+ }
+ visible := 0
+ for _, id := range found {
+ if hidden.CanSeeProject(id) {
+ visible++
+ }
+ }
+ if visible != len(ids) {
+ writeError(w, http.StatusBadRequest, "project not found")
+ return nil, false
+ }
+ return ids, true
+}
+
+// setGuestProjects makes ids exactly the projects userID is a member of. When
+// that adds or takes away a project, the guest's local search copy is made to
+// rebuild: nothing in those projects changed, so sync alone would neither
+// drop what it lost nor deliver what it gained.
+func setGuestProjects(r *http.Request, q *db.Queries, workspaceID, userID, addedBy pgtype.UUID, ids []pgtype.UUID) error {
+ removed, err := q.RemoveUserFromProjectsExcept(r.Context(), db.RemoveUserFromProjectsExceptParams{
+ WorkspaceID: workspaceID, UserID: userID, KeepProjectIds: ids,
+ })
+ if err != nil {
+ return err
+ }
+ added, err := q.AddUserToProjects(r.Context(), db.AddUserToProjectsParams{
+ WorkspaceID: workspaceID, UserID: userID, ProjectIds: ids, AddedBy: addedBy,
+ })
+ if err != nil {
+ return err
+ }
+ if removed == 0 && len(added) == 0 {
+ return nil
+ }
+ return markSearchAccessChanged(r.Context(), q, workspaceID, userID)
+}
+
+// markSearchAccessChanged records, in the caller's transaction, that what
+// userID can see changed without the content changing (MUL-9420). Local
+// search copies built before the transaction then rebuild under the new
+// access; see ListSearchIndexChanges.
+func markSearchAccessChanged(ctx context.Context, q *db.Queries, workspaceID, userID pgtype.UUID) error {
+ return q.MarkSearchAccessChanged(ctx, db.MarkSearchAccessChangedParams{
+ WorkspaceID: workspaceID, UserID: userID,
+ })
+}
+
+// beginMemberSeat takes a seat for a guest becoming a member the way an
+// invitation and its acceptance do: reserve, then consume, under one token
+// that stands in for the invitation. The caller moves the intent to confirm
+// in the role-change transaction. It returns uuid.Nil when seats are not
+// managed. A crash between the steps leaves a reservation with no
+// invitation, which the outbox worker releases.
+func (h *Handler) beginMemberSeat(ctx context.Context, workspaceID, userID uuid.UUID) (uuid.UUID, error) {
+ if !h.seatCapacityEnabled() {
+ return uuid.Nil, nil
+ }
+ token := uuid.New()
+ if err := h.reserveInvitationCapacity(ctx, workspaceID, token, time.Now().Add(guestSeatReservation)); err != nil {
+ return uuid.Nil, err
+ }
+ active, err := h.beginCapacityConsume(ctx, workspaceID, token, token, userID)
+ if err != nil {
+ h.compensateCapacityIntent(ctx, token)
+ return uuid.Nil, err
+ }
+ if !active {
+ return uuid.Nil, nil
+ }
+ return token, nil
+}
+
+const guestSeatReservation = time.Hour
+
+// demoteMemberToGuest revokes what a member holds that a guest may not (see
+// revokeAndDemoteToGuest) and releases the member's seat.
+func (h *Handler) demoteMemberToGuest(w http.ResponseWriter, r *http.Request, requester, target db.Member, projects []pgtype.UUID) (db.Member, bool) {
+ ctx := r.Context()
+ result, err := h.revokeAndDemoteToGuest(ctx, target.WorkspaceID, target.UserID, target.ID, requester.UserID, projects, target.Role)
+ if err != nil {
+ slog.Warn("demote member to guest failed", append(logger.RequestAttrs(r), "error", err, "member_id", uuidToString(target.ID))...)
+ writeMemberUpdateError(w, err)
+ return db.Member{}, false
+ }
+ h.settleMemberCapacityRelease(ctx, uuid.UUID(target.WorkspaceID.Bytes), uuid.UUID(target.ID.Bytes))
+ wsID := uuidToString(target.WorkspaceID)
+ logRevocation(result, wsID, uuidToString(target.UserID))
+ h.publishRevocation(ctx, result, wsID, "member", uuidToString(requester.UserID))
+ h.notifyDaemonWorkspacesChanged(uuidToString(target.UserID))
+ demoted := target
+ demoted.Role = projectaccess.RoleGuest
+ return demoted, true
+}
+
+// promoteGuest gives a guest a member role, taking a seat for it.
+func (h *Handler) promoteGuest(w http.ResponseWriter, r *http.Request, target db.Member, role string) (db.Member, bool) {
+ ctx := r.Context()
+ workspaceID := uuid.UUID(target.WorkspaceID.Bytes)
+ // A promoted guest takes a member slot like a new invitation does, so a
+ // full Free workspace refuses it the same way.
+ memberLimit, err := h.memberLimitFor(ctx, target.WorkspaceID, role, false)
+ if err != nil {
+ if errors.Is(err, errMemberLimitReached) {
+ writeMemberLimitReached(w)
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to update member")
+ }
+ return db.Member{}, false
+ }
+ token, err := h.beginMemberSeat(ctx, workspaceID, uuid.UUID(target.UserID.Bytes))
+ if err != nil {
+ writeSeatCapacityError(w, err)
+ return db.Member{}, false
+ }
+ compensate := func() {
+ if token != uuid.Nil {
+ h.compensateCapacityIntent(ctx, token)
+ }
+ }
+ fail := func() (db.Member, bool) {
+ compensate()
+ writeError(w, http.StatusInternalServerError, "failed to update member")
+ return db.Member{}, false
+ }
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return fail()
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if err := memberLimit.lock(ctx, qtx); err != nil {
+ return fail()
+ }
+ // Re-check under the row lock that the target is still a guest: a
+ // concurrent change that made it a member already took its seat.
+ if _, err := lockMemberRole(ctx, qtx, target.ID, projectaccess.RoleGuest); err != nil {
+ _ = tx.Rollback(ctx)
+ compensate()
+ writeMemberUpdateError(w, err)
+ return db.Member{}, false
+ }
+ limitAdmission, err := memberLimit.admit(ctx, qtx)
+ if err != nil {
+ _ = tx.Rollback(ctx)
+ if errors.Is(err, errMemberLimitReached) {
+ limitAdmission.record(ctx)
+ compensate()
+ writeMemberLimitReached(w)
+ return db.Member{}, false
+ }
+ return fail()
+ }
+ updated, err := qtx.UpdateMemberRole(ctx, db.UpdateMemberRoleParams{ID: target.ID, Role: role})
+ if err != nil {
+ return fail()
+ }
+ // The new member sees projects and project-less content its local
+ // search copy never received as a guest.
+ if err := markSearchAccessChanged(ctx, qtx, target.WorkspaceID, target.UserID); err != nil {
+ return fail()
+ }
+ if token != uuid.Nil {
+ if err := transitionCapacityIntentToConfirm(ctx, qtx, token, uuid.UUID(target.ID.Bytes), seatcapacity.ActionConsumeInvitation); err != nil {
+ _ = tx.Rollback(ctx)
+ return fail()
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ _ = tx.Rollback(ctx)
+ return fail()
+ }
+ limitAdmission.record(ctx)
+ if token != uuid.Nil {
+ h.confirmCapacityIntent(ctx, workspaceID, token, uuid.UUID(target.ID.Bytes))
+ }
+ return updated, true
+}
+
+type SetMemberProjectsRequest struct {
+ ProjectIDs []string `json:"project_ids"`
+}
+
+// SetMemberProjects replaces the projects a guest can see.
+// PUT /api/workspaces/{id}/members/{memberId}/projects
+func (h *Handler) SetMemberProjects(w http.ResponseWriter, r *http.Request) {
+ workspaceID := workspaceIDFromURL(r, "id")
+ requester, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ memberUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "memberId"), "member id")
+ if !ok {
+ return
+ }
+ target, err := h.Queries.GetMember(r.Context(), memberUUID)
+ if err != nil || target.WorkspaceID != requester.WorkspaceID {
+ writeError(w, http.StatusNotFound, "member not found")
+ return
+ }
+ if !projectaccess.IsGuestRole(target.Role) {
+ writeError(w, http.StatusBadRequest, "only a guest's projects are set here")
+ return
+ }
+ var req SetMemberProjectsRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ ids, ok := h.parseGuestProjectIDs(w, r, target.WorkspaceID, req.ProjectIDs)
+ if !ok {
+ return
+ }
+ added, err := h.Queries.CountProjectsUserIsNotMemberOf(r.Context(), db.CountProjectsUserIsNotMemberOfParams{
+ ProjectIds: ids, WorkspaceID: target.WorkspaceID, UserID: target.UserID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update projects")
+ return
+ }
+ // Only sharing another project widens the guest; narrowing never is.
+ var admission featureAdmission
+ if added > 0 {
+ if admission, ok = h.requireGuestAddition(w, r, target.WorkspaceID, "add_projects"); !ok {
+ return
+ }
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update projects")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+ // The target must still be a guest: a member made one meanwhile keeps
+ // its own projects, which this would otherwise overwrite.
+ if _, err := lockMemberRole(r.Context(), qtx, target.ID, projectaccess.RoleGuest); err != nil {
+ writeMemberUpdateError(w, err)
+ return
+ }
+ if err := setGuestProjects(r, qtx, target.WorkspaceID, target.UserID, requester.UserID, ids); err != nil {
+ slog.Warn("set guest projects failed", append(logger.RequestAttrs(r), "error", err, "member_id", uuidToString(target.ID))...)
+ writeError(w, http.StatusInternalServerError, "failed to update projects")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update projects")
+ return
+ }
+ admission.admitted(r.Context())
+
+ user, err := h.Queries.GetUser(r.Context(), target.UserID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load member")
+ return
+ }
+ resp := h.memberWithUserResponse(target, user)
+ resp.ProjectIDs = uuidsToStrings(ids)
+ h.publish(protocol.EventMemberUpdated, uuidToString(target.WorkspaceID), "member", requestUserID(r), map[string]any{
+ "member": resp,
+ })
+ writeJSON(w, http.StatusOK, resp)
+}
diff --git a/server/internal/handler/guest_boundaries_test.go b/server/internal/handler/guest_boundaries_test.go
new file mode 100644
index 0000000000..8072f04132
--- /dev/null
+++ b/server/internal/handler/guest_boundaries_test.go
@@ -0,0 +1,878 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ publicapiv1 "github.com/multica-ai/multica/server/pkg/publicapi/v1"
+)
+
+// Regression tests for the guest boundaries found in review of #10766
+// (MUL-9420). Each test fails on the code before the fix.
+
+// --- Plugins ---------------------------------------------------------------
+
+func pluginProblemCode(t *testing.T, rec *httptest.ResponseRecorder) string {
+ t.Helper()
+ var problem publicapiv1.Problem
+ if err := json.Unmarshal(rec.Body.Bytes(), &problem); err != nil {
+ t.Fatalf("decode problem %s: %v", rec.Body.String(), err)
+ }
+ return problem.Code
+}
+
+// A guest reaches no Plugin endpoint, through a surface session or a callback
+// token: neither the unshared project nor a write to its shared project.
+func TestPluginActionRefusesGuests(t *testing.T) {
+ f := newGuestFixture(t)
+ installationID := installPluginForAction(t, []string{"issues:read", "issues:write", "comments:read", "comments:write"})
+
+ asGuest := func(method, path, issue string, body any) *http.Request {
+ req := pluginActionRequest(method, path, installationID, body, map[string]string{"issue_ref": issue})
+ req.Header.Set("X-User-ID", f.guest)
+ return req
+ }
+
+ read := httptest.NewRecorder()
+ testHandler.GetPluginIssue(read, asGuest(http.MethodGet, "/v1/issues/"+f.otherIssue, f.otherIssue, nil))
+ if read.Code != http.StatusForbidden || pluginProblemCode(t, read) != "guest_not_allowed" {
+ t.Fatalf("guest plugin read of an unshared issue = %d %s, want 403 guest_not_allowed", read.Code, read.Body.String())
+ }
+
+ var before string
+ dbfx.QueryRow(t, `SELECT title FROM issue WHERE id = $1`, f.sharedIssue).Scan(&before)
+ patch := httptest.NewRecorder()
+ testHandler.PatchPluginIssue(patch, asGuest(http.MethodPatch, "/v1/issues/"+f.sharedIssue, f.sharedIssue,
+ map[string]any{"title": "renamed by a guest"}))
+ if patch.Code != http.StatusForbidden {
+ t.Fatalf("guest plugin patch of its shared issue = %d %s, want 403", patch.Code, patch.Body.String())
+ }
+ var after string
+ dbfx.QueryRow(t, `SELECT title FROM issue WHERE id = $1`, f.sharedIssue).Scan(&after)
+ if after != before {
+ t.Fatalf("title = %q after a refused guest patch, want %q", after, before)
+ }
+
+ withCallbackTokens(t)
+ token := issueCallbackToken(t, installationID, service.HookActor{Type: "member", ID: parseUUID(f.guest)})
+ cb := httptest.NewRecorder()
+ testHandler.GetPluginIssue(cb, callbackRequest(token, http.MethodGet, "/v1/issues/"+f.otherIssue, nil,
+ map[string]string{"issue_ref": f.otherIssue}))
+ if cb.Code != http.StatusForbidden || pluginProblemCode(t, cb) != "guest_not_allowed" {
+ t.Fatalf("guest callback read = %d %s, want 403 guest_not_allowed", cb.Code, cb.Body.String())
+ }
+}
+
+// A call acting as a member reaches only the private projects that member is
+// in, as the ordinary issue endpoint does.
+func TestPluginActionHidesPrivateProjectsFromMembers(t *testing.T) {
+ f := newGuestFixture(t)
+ installationID := installPluginForAction(t, []string{"issues:read"})
+ outsider := createPlainMember(t, f.marker+"[email protected]")
+
+ get := func(userID string) int {
+ req := pluginActionRequest(http.MethodGet, "/v1/issues/"+f.secretIssue, installationID, nil, map[string]string{"issue_ref": f.secretIssue})
+ req.Header.Set("X-User-ID", userID)
+ rec := httptest.NewRecorder()
+ testHandler.GetPluginIssue(rec, req)
+ return rec.Code
+ }
+ if code := get(outsider); code != http.StatusNotFound {
+ t.Fatalf("member outside the private project: plugin read = %d, want 404", code)
+ }
+ if code := get(testUserID); code != http.StatusOK {
+ t.Fatalf("member of the private project: plugin read = %d, want 200", code)
+ }
+}
+
+// --- Agents, runs, attachments and mentions -------------------------------
+
+// A guest is shown the agents it meets in its projects, not the directory.
+func TestGuestAgentListHasOnlyAgentsInItsProjects(t *testing.T) {
+ f := newGuestFixture(t)
+ met := dbfx.Agent(t, f.marker+" met", "")
+ elsewhere := dbfx.Agent(t, f.marker+" elsewhere", "")
+ archived := dbfx.Agent(t, f.marker+" archived", "", testutil.Cols{"archived_at": time.Now()})
+ dbfx.Comment(t, f.sharedIssue, "agent reply", testutil.Cols{"author_type": "agent", "author_id": met})
+ dbfx.Comment(t, f.otherIssue, "agent reply", testutil.Cols{"author_type": "agent", "author_id": elsewhere})
+
+ for _, path := range []string{"/api/agents", "/api/agents?include_archived=true"} {
+ var agents []AgentResponse
+ guestRequest(t, testHandler.ListAgents, f.guest, http.MethodGet, path, nil).Want(http.StatusOK).JSON(&agents)
+ seen := map[string]bool{}
+ for _, a := range agents {
+ seen[a.ID] = true
+ }
+ if !seen[met] {
+ t.Errorf("%s: guest misses the agent that replied in its project", path)
+ }
+ if seen[elsewhere] || seen[archived] {
+ t.Errorf("%s: guest sees agents outside its projects: %v", path, seen)
+ }
+ }
+}
+
+// A guest learns that an agent is working on its issue, not where or how.
+func TestGuestActiveTaskHasNoRunDetails(t *testing.T) {
+ f := newGuestFixture(t)
+ runtime := dbfx.Runtime(t, f.marker+" runtime")
+ agent := dbfx.Agent(t, f.marker+" worker", runtime)
+ dbfx.Task(t, agent, testutil.Cols{
+ "issue_id": f.sharedIssue, "status": "running", "runtime_id": runtime,
+ "work_dir": "/Users/alice/work/secret-repo", "handoff_note": "use the staging credentials",
+ })
+
+ get := func(userID string) string {
+ return guestRequest(t, testHandler.GetActiveTaskForIssue, userID, http.MethodGet,
+ "/api/issues/"+f.sharedIssue+"/active-task", nil, "id", f.sharedIssue).Want(http.StatusOK).Body.String()
+ }
+ guest := get(f.guest)
+ for _, leak := range []string{"secret-repo", "staging credentials", "work_dir", "handoff_note"} {
+ if strings.Contains(guest, leak) {
+ t.Errorf("guest active-task carries %q: %s", leak, guest)
+ }
+ }
+ if !strings.Contains(guest, agent) || !strings.Contains(guest, f.sharedIssue) {
+ t.Errorf("guest active-task lost the agent or issue: %s", guest)
+ }
+ if member := get(testUserID); !strings.Contains(member, "staging credentials") {
+ t.Errorf("member active-task lost the handoff note: %s", member)
+ }
+}
+
+func uploadToComment(t *testing.T, userID, commentID string) *httptest.ResponseRecorder {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", "note.png")
+ if err != nil {
+ t.Fatal(err)
+ }
+ part.Write([]byte("\x89PNG\r\n\x1a\nrest-of-bytes"))
+ writer.WriteField("comment_id", commentID)
+ writer.Close()
+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", userID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ rec := httptest.NewRecorder()
+ testHandler.UploadFile(rec, req)
+ return rec
+}
+
+// A guest attaches files only to its own comments.
+func TestGuestUploadsOnlyToItsOwnComments(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+ f := newGuestFixture(t)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE uploader_id = $1`, f.guest)
+ })
+ others := dbfx.Comment(t, f.sharedIssue, "member comment", testutil.Cols{"author_type": "member", "author_id": testUserID})
+ own := dbfx.Comment(t, f.sharedIssue, "guest comment", testutil.Cols{"author_type": "member", "author_id": f.guest})
+
+ if rec := uploadToComment(t, f.guest, others); rec.Code != http.StatusForbidden {
+ t.Errorf("guest upload to someone else's comment = %d %s, want 403", rec.Code, rec.Body.String())
+ }
+ if rec := uploadToComment(t, f.guest, own); rec.Code != http.StatusOK {
+ t.Errorf("guest upload to its own comment = %d %s, want 200", rec.Code, rec.Body.String())
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE comment_id = $1`, others); n != 0 {
+ t.Errorf("someone else's comment has %d guest attachments, want 0", n)
+ }
+}
+
+func uploadDraftToIssue(t *testing.T, userID, issueID string) AttachmentResponse {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", "draft.png")
+ if err != nil {
+ t.Fatal(err)
+ }
+ part.Write([]byte("\x89PNG\r\n\x1a\nrest-of-bytes"))
+ writer.WriteField("issue_id", issueID)
+ writer.Close()
+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", userID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ rec := httptest.NewRecorder()
+ testHandler.UploadFile(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("upload draft = %d %s, want 200", rec.Code, rec.Body.String())
+ }
+ var att AttachmentResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &att); err != nil {
+ t.Fatal(err)
+ }
+ return att
+}
+
+func attachmentBinding(t *testing.T, id string) (issueID, commentID *string) {
+ t.Helper()
+ dbfx.QueryRow(t, `SELECT issue_id::text, comment_id::text FROM attachment WHERE id = $1`, id).Scan(&issueID, &commentID)
+ return issueID, commentID
+}
+
+// A guest's comment draft upload does not touch the issue: it stays unbound
+// until the guest's comment (new or edited) takes it. A member's upload still
+// attaches to the issue at once.
+func TestGuestDraftUploadBindsOnlyWithItsComment(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+ f := newGuestFixture(t)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE issue_id = $1 OR uploader_id = $2`, f.sharedIssue, f.guest)
+ })
+ revision := func() int64 {
+ var rev int64
+ dbfx.QueryRow(t, `SELECT revision FROM issue WHERE id = $1`, f.sharedIssue).Scan(&rev)
+ return rev
+ }
+
+ before := revision()
+ draft := uploadDraftToIssue(t, f.guest, f.sharedIssue)
+ if issueID, commentID := attachmentBinding(t, draft.ID); issueID != nil || commentID != nil {
+ t.Fatalf("guest draft bound to issue %v comment %v before any comment, want unbound", issueID, commentID)
+ }
+ if got := revision(); got != before {
+ t.Fatalf("issue revision %d -> %d from a guest draft upload, want unchanged", before, got)
+ }
+ var listed []AttachmentResponse
+ guestRequest(t, testHandler.ListAttachments, testUserID, http.MethodGet, "/api/issues/"+f.sharedIssue+"/attachments", nil, "id", f.sharedIssue).
+ Want(http.StatusOK).JSON(&listed)
+ for _, a := range listed {
+ if a.ID == draft.ID {
+ t.Fatal("the issue's attachments list a guest draft before its comment is sent")
+ }
+ }
+
+ var comment CommentResponse
+ guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "with a file", AttachmentIDs: []string{draft.ID}}, "id", f.sharedIssue).
+ Want(http.StatusCreated).JSON(&comment)
+ if issueID, commentID := attachmentBinding(t, draft.ID); issueID == nil || *issueID != f.sharedIssue || commentID == nil || *commentID != comment.ID {
+ t.Fatalf("guest draft after its comment: issue %v comment %v, want the issue and the comment", issueID, commentID)
+ }
+
+ // Editing its comment takes a new draft the same way.
+ second := uploadDraftToIssue(t, f.guest, f.sharedIssue)
+ guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut, "/api/comments/"+comment.ID,
+ map[string]any{"content": "with two files", "attachment_ids": []string{draft.ID, second.ID}}, "commentId", comment.ID).
+ Want(http.StatusOK)
+ if issueID, commentID := attachmentBinding(t, second.ID); issueID == nil || *issueID != f.sharedIssue || commentID == nil || *commentID != comment.ID {
+ t.Fatalf("guest edit draft: issue %v comment %v, want the issue and the comment", issueID, commentID)
+ }
+
+ // Removing both files from its comment takes them off the issue too: they
+ // go back to being the guest's drafts.
+ guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut, "/api/comments/"+comment.ID,
+ map[string]any{"content": "no files", "attachment_ids": []string{}}, "commentId", comment.ID).
+ Want(http.StatusOK)
+ for _, id := range []string{draft.ID, second.ID} {
+ if issueID, commentID := attachmentBinding(t, id); issueID != nil || commentID != nil {
+ t.Fatalf("guest file removed from its comment: issue %v comment %v, want unbound", issueID, commentID)
+ }
+ }
+ guestRequest(t, testHandler.ListAttachments, testUserID, http.MethodGet, "/api/issues/"+f.sharedIssue+"/attachments", nil, "id", f.sharedIssue).
+ Want(http.StatusOK).JSON(&listed)
+ for _, a := range listed {
+ if a.ID == draft.ID || a.ID == second.ID {
+ t.Fatal("the issue still lists a file the guest removed from its comment")
+ }
+ }
+
+ // A member's upload attaches to the issue as before, and stays there when
+ // removed from the member's comment.
+ memberUpload := uploadDraftToIssue(t, testUserID, f.sharedIssue)
+ if issueID, _ := attachmentBinding(t, memberUpload.ID); issueID == nil || *issueID != f.sharedIssue {
+ t.Fatalf("member upload issue = %v, want bound to the issue", issueID)
+ }
+ var memberComment CommentResponse
+ guestRequest(t, testHandler.CreateComment, testUserID, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "member file", AttachmentIDs: []string{memberUpload.ID}}, "id", f.sharedIssue).
+ Want(http.StatusCreated).JSON(&memberComment)
+ guestRequest(t, testHandler.UpdateComment, testUserID, http.MethodPut, "/api/comments/"+memberComment.ID,
+ map[string]any{"content": "member file removed", "attachment_ids": []string{}}, "commentId", memberComment.ID).
+ Want(http.StatusOK)
+ if issueID, commentID := attachmentBinding(t, memberUpload.ID); issueID == nil || *issueID != f.sharedIssue || commentID != nil {
+ t.Fatalf("member file removed from its comment: issue %v comment %v, want kept on the issue", issueID, commentID)
+ }
+}
+
+// waitForLockWaiters blocks until at least n other backends of this database
+// wait on a lock.
+func waitForLockWaiters(t *testing.T, n int) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ var waiting int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM pg_stat_activity
+ WHERE datname = current_database() AND wait_event_type = 'Lock' AND pid <> pg_backend_pid()`).Scan(&waiting); err != nil {
+ t.Fatal(err)
+ }
+ if waiting >= n {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("%d backends waiting on a lock, want %d", waiting, n)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// Publishing a comment and editing another one with the same draft take the
+// draft and the issue in the same order, so they never deadlock: the issue
+// lock is held while the edit and then the publish queue behind it.
+func TestCommentEditAndCreateWithSameDraftDoNotDeadlock(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+ f := newGuestFixture(t)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE uploader_id = $1`, f.guest)
+ })
+ var existing CommentResponse
+ guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "to be edited"}, "id", f.sharedIssue).Want(http.StatusCreated).JSON(&existing)
+ draft := uploadDraftToIssue(t, f.guest, f.sharedIssue)
+
+ ctx := context.Background()
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `SELECT 1 FROM issue WHERE id = $1 FOR UPDATE`, f.sharedIssue); err != nil {
+ t.Fatal(err)
+ }
+
+ var wg sync.WaitGroup
+ var edit, create *testutil.Response
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ edit = guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut, "/api/comments/"+existing.ID,
+ map[string]any{"content": "edited with the draft", "attachment_ids": []string{draft.ID}}, "commentId", existing.ID)
+ }()
+ waitForLockWaiters(t, 1)
+ go func() {
+ defer wg.Done()
+ create = guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "published with the draft", AttachmentIDs: []string{draft.ID}}, "id", f.sharedIssue)
+ }()
+ waitForLockWaiters(t, 2)
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ wg.Wait()
+
+ for name, resp := range map[string]*testutil.Response{"edit": edit, "create": create} {
+ if resp.Code >= http.StatusInternalServerError {
+ t.Errorf("%s = %d %s, want no server error", name, resp.Code, resp.Body.String())
+ }
+ }
+ if edit.Code != http.StatusOK {
+ t.Fatalf("edit = %d %s, want 200: it queued first", edit.Code, edit.Body.String())
+ }
+ // The edit took the draft; the publish is refused instead of failing.
+ if create.Code != http.StatusConflict {
+ t.Fatalf("create = %d %s, want 409 for a draft the edit already took", create.Code, create.Body.String())
+ }
+ if _, commentID := attachmentBinding(t, draft.ID); commentID == nil || *commentID != existing.ID {
+ t.Fatalf("draft comment = %v, want the edited comment", commentID)
+ }
+}
+
+// Editing a comment applies the same mention rule as creating one.
+func TestGuestCommentMentionRuleCoversCreateAndEdit(t *testing.T) {
+ f := newGuestFixture(t)
+ agent := dbfx.Agent(t, f.marker+" mentioned", "")
+ agentMention := fmt.Sprintf("[@a](mention://agent/%s) please", agent)
+ allMention := "[@All](mention://all/all) heads up"
+
+ create := func(content string) *testutil.Response {
+ return guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost,
+ "/api/issues/"+f.sharedIssue+"/comments", CreateCommentRequest{Content: content}, "id", f.sharedIssue)
+ }
+ create(allMention).Want(http.StatusForbidden)
+
+ var comment CommentResponse
+ create("first draft").Want(http.StatusCreated).JSON(&comment)
+ edit := func(content string) *testutil.Response {
+ return guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut,
+ "/api/comments/"+comment.ID, map[string]any{"content": content}, "commentId", comment.ID)
+ }
+ edit(agentMention).Want(http.StatusForbidden)
+ edit(allMention).Want(http.StatusForbidden)
+ edit("second draft").Want(http.StatusOK)
+
+ var content string
+ dbfx.QueryRow(t, `SELECT content FROM comment WHERE id = $1`, comment.ID).Scan(&content)
+ if content != "second draft" {
+ t.Fatalf("comment content = %q, want the last allowed edit", content)
+ }
+}
+
+// A guest deletes its own comment through the path that keeps replies.
+func TestGuestMayDeleteOwnCommentKeepingReplies(t *testing.T) {
+ f := newGuestFixture(t)
+ ok := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }
+ rec := guestRequest(t, ok, f.guest, http.MethodDelete, "/api/comments/"+f.sharedIssue+"/keep-replies", nil)
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf("guest DELETE keep-replies = %d, want the route allowed", rec.Code)
+ }
+}
+
+// --- Local search after losing access --------------------------------------
+
+func searchChangesAs(t *testing.T, userID, cursor string) *testutil.Response {
+ t.Helper()
+ req := asUser(searchIndexRequest(http.MethodPost, "/api/search-index/changes", testWorkspaceID,
+ map[string]any{"cursor": cursor, "limit": 1}), userID)
+ return testutil.Call(t, testHandler.ListSearchIndexChanges, req)
+}
+
+func searchCursorAs(t *testing.T, userID string) string {
+ t.Helper()
+ var manifest SearchIndexManifestResponse
+ req := asUser(searchIndexRequest(http.MethodGet, "/api/search-index/manifest", testWorkspaceID, nil), userID)
+ testutil.Call(t, testHandler.GetSearchIndexManifest, req).Want(http.StatusOK).JSON(&manifest)
+ return manifest.Cursor
+}
+
+// A member made a guest, and a guest losing a project, must rebuild a local
+// copy built before: nothing it can no longer see was rewritten, so sync
+// alone would keep it.
+func TestSearchIndexRebuildsAfterGuestAccessNarrows(t *testing.T) {
+ f := newGuestFixture(t)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM member_search_access WHERE workspace_id = $1`, testWorkspaceID)
+ })
+ member := createPlainMember(t, f.marker+"[email protected]")
+ var memberID string
+ dbfx.QueryRow(t, `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, member).Scan(&memberID)
+
+ memberCursor := searchCursorAs(t, member)
+ ownerCursor := searchCursorAs(t, testUserID)
+ searchChangesAs(t, member, memberCursor).Want(http.StatusOK)
+
+ demote := withURLParams(newRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/members/"+memberID,
+ UpdateMemberRequest{Role: "guest", ProjectIDs: []string{f.shared}}), "id", testWorkspaceID, "memberId", memberID)
+ testutil.Call(t, testHandler.UpdateMember, demote).Want(http.StatusOK)
+
+ searchChangesAs(t, member, memberCursor).Want(http.StatusGone)
+ // Nobody else's copy is affected.
+ searchChangesAs(t, testUserID, ownerCursor).Want(http.StatusOK)
+ // A copy built after the demotion syncs normally.
+ rebuilt := searchCursorAs(t, member)
+ searchChangesAs(t, member, rebuilt).Want(http.StatusOK)
+
+ // Re-sending the same projects changes nothing.
+ path := "/api/workspaces/" + testWorkspaceID + "/members/" + memberID + "/projects"
+ setProjects := func(ids ...string) {
+ t.Helper()
+ req := withURLParams(newRequest(http.MethodPut, path, SetMemberProjectsRequest{ProjectIDs: ids}),
+ "id", testWorkspaceID, "memberId", memberID)
+ testutil.Call(t, testHandler.SetMemberProjects, req).Want(http.StatusOK)
+ }
+ setProjects(f.shared)
+ searchChangesAs(t, member, rebuilt).Want(http.StatusOK)
+
+ // Sharing another project: its existing issues and comments were not
+ // rewritten, so only a rebuild delivers them.
+ setProjects(f.shared, f.other)
+ searchChangesAs(t, member, rebuilt).Want(http.StatusGone)
+
+ // Taking one away.
+ beforeNarrow := searchCursorAs(t, member)
+ setProjects(f.shared)
+ searchChangesAs(t, member, beforeNarrow).Want(http.StatusGone)
+
+ // Becoming a member: every project and project-less issue is new to it.
+ beforePromotion := searchCursorAs(t, member)
+ promote := withURLParams(newRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/members/"+memberID,
+ UpdateMemberRequest{Role: "member"}), "id", testWorkspaceID, "memberId", memberID)
+ testutil.Call(t, testHandler.UpdateMember, promote).Want(http.StatusOK)
+ searchChangesAs(t, member, beforePromotion).Want(http.StatusGone)
+}
+
+// --- Plan and rollout gate on every guest addition --------------------------
+
+// Project member management shares a project with a guest only when guests
+// can be added; members, and guests already in the project, are unaffected.
+func TestProjectSharingWithGuestFollowsThePlanAndFlag(t *testing.T) {
+ f := newGuestFixture(t)
+ addTo := func(project string, ids ...string) *testutil.Response {
+ req := withURLParam(newRequest(http.MethodPost, "/api/projects/"+project+"/members", map[string]any{"user_ids": ids}), "id", project)
+ return testutil.Call(t, testHandler.AddProjectMembers, req)
+ }
+ update := func(project string, body map[string]any) *testutil.Response {
+ req := withURLParam(newRequest(http.MethodPut, "/api/projects/"+project, body), "id", project)
+ return testutil.Call(t, testHandler.UpdateProject, req)
+ }
+
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce})
+ wantGuestsLocked(t, addTo(f.other, f.guest))
+ wantGuestsLocked(t, update(f.secret, map[string]any{"member_ids": []string{f.guest}}))
+ if got := guestProjectIDs(t, f.guest); fmt.Sprint(got) != fmt.Sprint([]string{f.shared}) {
+ t.Fatalf("guest projects after refused shares = %v, want only shared", got)
+ }
+ // The guest's existing project stays, and re-sending it adds nothing.
+ addTo(f.shared, f.guest).Want(http.StatusOK)
+ // Members are not guests.
+ member := createPlainMember(t, f.marker+"[email protected]")
+ update(f.secret, map[string]any{"member_ids": []string{member}}).Want(http.StatusOK)
+
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionOff})
+ withFeatureFlag(t, testHandler, featureflags.WorkspaceGuests, false)
+ resp := addTo(f.other, f.guest)
+ if resp.Code != http.StatusForbidden || !strings.Contains(resp.Body.String(), "workspace_guests_disabled") {
+ t.Fatalf("share with a guest while guests are off = %d %s, want 403 workspace_guests_disabled", resp.Code, resp.Body.String())
+ }
+ if got := guestProjectIDs(t, f.guest); fmt.Sprint(got) != fmt.Sprint([]string{f.shared}) {
+ t.Fatalf("guest projects with guests off = %v, want only shared", got)
+ }
+ // The existing guest keeps reading its project.
+ if rec := guestRequest(t, testHandler.GetIssue, f.guest, http.MethodGet, "/api/issues/"+f.sharedIssue, nil, "id", f.sharedIssue); rec.Code != http.StatusOK {
+ t.Fatalf("existing guest GET shared issue with guests off = %d, want 200", rec.Code)
+ }
+}
+
+// A guest invitation sent while guests could be added is not accepted after
+// the plan or the rollout switch stops allowing them; it stays pending.
+func TestGuestInvitationAcceptanceFollowsThePlanAndFlag(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ f := newGuestFixture(t)
+ email := f.marker + "[email protected]"
+ invitee := dbfx.User(t, "Late Guest", email)
+ dbfx.Cleanup(t, `DELETE FROM member WHERE user_id = $1`, invitee)
+
+ var inv InvitationResponse
+ req := withURLParam(newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members",
+ CreateMemberRequest{Email: email, Role: "guest", ProjectIDs: []string{f.shared}}), "id", testWorkspaceID)
+ testutil.Call(t, testHandler.CreateInvitation, req).Want(http.StatusCreated).JSON(&inv)
+
+ accept := func() *testutil.Response {
+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/invitations/"+inv.ID+"/accept", nil), invitee), "id", inv.ID)
+ return testutil.Call(t, testHandler.AcceptInvitation, req)
+ }
+ wantPending := func(label string) {
+ t.Helper()
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM workspace_invitation WHERE id = $1`, inv.ID).Scan(&status)
+ if status != "pending" {
+ t.Fatalf("%s: invitation status = %q, want pending", label, status)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, invitee); n != 0 {
+ t.Fatalf("%s: invitee became a member", label)
+ }
+ }
+
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce})
+ wantGuestsLocked(t, accept())
+ wantPending("plan without guests")
+
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionOff})
+ withFeatureFlag(t, testHandler, featureflags.WorkspaceGuests, false)
+ if resp := accept(); resp.Code != http.StatusForbidden || !strings.Contains(resp.Body.String(), "workspace_guests_disabled") {
+ t.Fatalf("accept with guests off = %d %s, want 403 workspace_guests_disabled", resp.Code, resp.Body.String())
+ }
+ wantPending("guests off")
+
+ withFeatureFlag(t, testHandler, featureflags.WorkspaceGuests, true)
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionObserve})
+ accept().Want(http.StatusOK)
+ if got := guestAttempts(t); got.observed != 1 || got.lastOperation != "accept_invitation" {
+ t.Fatalf("guest attempts after an observed acceptance = %+v, want one observed accept_invitation", got)
+ }
+}
+
+// --- Concurrent role changes -----------------------------------------------
+
+// raceRoleChange holds the target's member row locked, starts the request,
+// waits until the request blocks on that lock (it has read the target's
+// role by then), commits the concurrent change, and returns the response.
+func raceRoleChange(t *testing.T, memberID, concurrentRole string, request func() *testutil.Response) *testutil.Response {
+ t.Helper()
+ ctx := context.Background()
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `SELECT 1 FROM member WHERE id = $1 FOR UPDATE`, memberID); err != nil {
+ t.Fatal(err)
+ }
+
+ var wg sync.WaitGroup
+ var resp *testutil.Response
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ resp = request()
+ }()
+
+ deadline := time.Now().Add(10 * time.Second)
+ for !blockedOnMember(t, memberID) {
+ if time.Now().After(deadline) {
+ t.Fatal("request never blocked on the member row")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+
+ if _, err := tx.Exec(ctx, `UPDATE member SET role = $2 WHERE id = $1`, memberID, concurrentRole); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ wg.Wait()
+ return resp
+}
+
+// blockedOnMember reports whether another backend waits for the lock on
+// this member's row.
+func blockedOnMember(t *testing.T, memberID string) bool {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM pg_stat_activity a
+ WHERE a.wait_event_type = 'Lock' AND a.pid <> pg_backend_pid()
+ AND a.query ILIKE '%member%'
+ AND EXISTS (SELECT 1 FROM pg_locks l WHERE l.pid = a.pid AND NOT l.granted)`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n > 0
+}
+
+func wantRoleChanged(t *testing.T, resp *testutil.Response) {
+ t.Helper()
+ if resp.Code != http.StatusConflict || !strings.Contains(resp.Body.String(), "member_role_changed") {
+ t.Fatalf("stale role change = %d %s, want 409 member_role_changed", resp.Code, resp.Body.String())
+ }
+}
+
+func memberRole(t *testing.T, memberID string) string {
+ t.Helper()
+ var role string
+ dbfx.QueryRow(t, `SELECT role FROM member WHERE id = $1`, memberID).Scan(&role)
+ return role
+}
+
+// A request decided on "member" must not write over a demotion that
+// committed first: making the guest an admin that way would skip the seat.
+func TestRoleChangeDecidedOnStaleRoleIsRefused(t *testing.T) {
+ f := newGuestFixture(t)
+ member := createPlainMember(t, f.marker+"[email protected]")
+ var memberID string
+ dbfx.QueryRow(t, `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, member).Scan(&memberID)
+ path := "/api/workspaces/" + testWorkspaceID + "/members/" + memberID
+ patch := func(body UpdateMemberRequest) func() *testutil.Response {
+ return func() *testutil.Response {
+ req := withURLParams(newRequest(http.MethodPatch, path, body), "id", testWorkspaceID, "memberId", memberID)
+ return testutil.Call(t, testHandler.UpdateMember, req)
+ }
+ }
+
+ // member -> admin, while a demotion to guest commits first.
+ wantRoleChanged(t, raceRoleChange(t, memberID, "guest", patch(UpdateMemberRequest{Role: "admin"})))
+ if role := memberRole(t, memberID); role != "guest" {
+ t.Fatalf("role = %q, want the committed guest", role)
+ }
+
+ // guest -> member, while another promotion commits first: the stale
+ // request must not take a second seat or rewrite the role.
+ wantRoleChanged(t, raceRoleChange(t, memberID, "member", patch(UpdateMemberRequest{Role: "member"})))
+ if role := memberRole(t, memberID); role != "member" {
+ t.Fatalf("role = %q, want the committed member", role)
+ }
+
+ // member -> guest, while a promotion to admin commits first.
+ wantRoleChanged(t, raceRoleChange(t, memberID, "admin",
+ patch(UpdateMemberRequest{Role: "guest", ProjectIDs: []string{f.shared}})))
+ if role := memberRole(t, memberID); role != "admin" {
+ t.Fatalf("role = %q, want the committed admin", role)
+ }
+
+ // Setting a guest's projects after it was made a member leaves the
+ // member's projects alone.
+ dbfx.Exec(t, `UPDATE member SET role = 'guest' WHERE id = $1`, memberID)
+ addProjectMemberRow(t, f.other, member)
+ setProjects := func() *testutil.Response {
+ req := withURLParams(newRequest(http.MethodPut, path+"/projects", SetMemberProjectsRequest{ProjectIDs: []string{f.shared}}),
+ "id", testWorkspaceID, "memberId", memberID)
+ return testutil.Call(t, testHandler.SetMemberProjects, req)
+ }
+ wantRoleChanged(t, raceRoleChange(t, memberID, "member", setProjects))
+ if got := guestProjectIDs(t, member); fmt.Sprint(got) != fmt.Sprint([]string{f.other}) {
+ t.Fatalf("member projects = %v, want untouched", got)
+ }
+}
+
+// An unbound draft joins only its uploader's comment. A guest's file taken
+// off its comment cannot be adopted by another guest (or a member) who
+// learned its id, on create or on edit.
+func TestDraftAttachmentJoinsOnlyItsUploadersComment(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+ f := newGuestFixture(t)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE uploader_id = $1`, f.guest)
+ })
+ other := createPlainMember(t, f.marker+"[email protected]")
+ dbfx.Exec(t, `UPDATE member SET role = 'guest' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, other)
+ addProjectMemberRow(t, f.other, other)
+
+ // The guest attaches a file and takes it off again: an unbound draft.
+ draft := uploadDraftToIssue(t, f.guest, f.sharedIssue)
+ var own CommentResponse
+ guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "with a file", AttachmentIDs: []string{draft.ID}}, "id", f.sharedIssue).
+ Want(http.StatusCreated).JSON(&own)
+ guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut, "/api/comments/"+own.ID,
+ map[string]any{"content": "file removed", "attachment_ids": []string{}}, "commentId", own.ID).Want(http.StatusOK)
+
+ wantUnbound := func(label string) {
+ t.Helper()
+ if issueID, commentID := attachmentBinding(t, draft.ID); issueID != nil || commentID != nil {
+ t.Fatalf("%s: draft bound to issue %v comment %v, want still unbound", label, issueID, commentID)
+ }
+ }
+ for _, adopter := range []string{other, testUserID} {
+ issue := f.otherIssue
+ guestRequest(t, testHandler.CreateComment, adopter, http.MethodPost, "/api/issues/"+issue+"/comments",
+ CreateCommentRequest{Content: "adopting", AttachmentIDs: []string{draft.ID}}, "id", issue).
+ Want(http.StatusConflict)
+ wantUnbound("create by another user")
+
+ var theirs CommentResponse
+ guestRequest(t, testHandler.CreateComment, adopter, http.MethodPost, "/api/issues/"+issue+"/comments",
+ CreateCommentRequest{Content: "plain"}, "id", issue).Want(http.StatusCreated).JSON(&theirs)
+ guestRequest(t, testHandler.UpdateComment, adopter, http.MethodPut, "/api/comments/"+theirs.ID,
+ map[string]any{"content": "adopting on edit", "attachment_ids": []string{draft.ID}}, "commentId", theirs.ID).
+ Want(http.StatusConflict)
+ wantUnbound("edit by another user")
+ }
+
+ // Its uploader can still use it.
+ guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut, "/api/comments/"+own.ID,
+ map[string]any{"content": "file back", "attachment_ids": []string{draft.ID}}, "commentId", own.ID).Want(http.StatusOK)
+ if _, commentID := attachmentBinding(t, draft.ID); commentID == nil || *commentID != own.ID {
+ t.Fatalf("draft comment = %v, want back on its uploader's comment", commentID)
+ }
+}
+
+// When a comment published with a draft wins the race, an edit asking for
+// the same draft is refused and rolled back, not saved without the file.
+func TestCommentEditLosingDraftToPublishIsRefused(t *testing.T) {
+ origStorage := testHandler.Storage
+ testHandler.Storage = &mockStorage{}
+ t.Cleanup(func() { testHandler.Storage = origStorage })
+ f := newGuestFixture(t)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE uploader_id = $1`, f.guest)
+ })
+ var existing CommentResponse
+ guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "before the edit"}, "id", f.sharedIssue).Want(http.StatusCreated).JSON(&existing)
+ draft := uploadDraftToIssue(t, f.guest, f.sharedIssue)
+
+ ctx := context.Background()
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `SELECT 1 FROM issue WHERE id = $1 FOR UPDATE`, f.sharedIssue); err != nil {
+ t.Fatal(err)
+ }
+
+ var wg sync.WaitGroup
+ var create, edit *testutil.Response
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ create = guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost, "/api/issues/"+f.sharedIssue+"/comments",
+ CreateCommentRequest{Content: "published with the draft", AttachmentIDs: []string{draft.ID}}, "id", f.sharedIssue)
+ }()
+ waitForLockWaiters(t, 1) // the publish holds the draft and waits for the issue
+ go func() {
+ defer wg.Done()
+ edit = guestRequest(t, testHandler.UpdateComment, f.guest, http.MethodPut, "/api/comments/"+existing.ID,
+ map[string]any{"content": "edited with the draft", "attachment_ids": []string{draft.ID}}, "commentId", existing.ID)
+ }()
+ waitForLockWaiters(t, 2) // the edit waits for the draft
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ wg.Wait()
+
+ if create.Code != http.StatusCreated {
+ t.Fatalf("create = %d %s, want 201: it queued first", create.Code, create.Body.String())
+ }
+ if edit.Code != http.StatusConflict {
+ t.Fatalf("edit = %d %s, want 409 for a draft the publish already took", edit.Code, edit.Body.String())
+ }
+ var content string
+ dbfx.QueryRow(t, `SELECT content FROM comment WHERE id = $1`, existing.ID).Scan(&content)
+ if content != "before the edit" {
+ t.Fatalf("edited comment content = %q, want the refused edit rolled back", content)
+ }
+}
+
+// An installed client edits without expected_revision or content_base. When
+// such an edit also sets attachments and one is no longer available, it is
+// refused as a whole: the runs queued from the old body stay queued, and the
+// request does not hang on its own transaction's issue lock.
+func TestLegacyCommentEditWithUnavailableAttachmentKeepsQueuedRun(t *testing.T) {
+ f := newGuestFixture(t)
+ runtime := dbfx.Runtime(t, f.marker+" legacy runtime")
+ agent := dbfx.Agent(t, f.marker+" legacy agent", runtime)
+ comment := dbfx.Comment(t, f.sharedIssue, "please look", testutil.Cols{"author_type": "member", "author_id": testUserID})
+ task := dbfx.Task(t, agent, testutil.Cols{
+ "issue_id": f.sharedIssue, "runtime_id": runtime, "trigger_comment_id": comment,
+ })
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+comment,
+ map[string]any{"content": "please look again", "attachment_ids": []string{uuid.NewString()}}), "commentId", comment)
+ resp := testutil.Call(t, testHandler.UpdateComment, req.WithContext(context.WithValue(ctx, chi.RouteCtxKey, chi.RouteContext(req.Context()))))
+ if ctx.Err() != nil {
+ t.Fatalf("legacy edit did not finish within 10s (status %d)", resp.Code)
+ }
+ if resp.Code != http.StatusConflict {
+ t.Fatalf("legacy edit with an unavailable attachment = %d %s, want 409", resp.Code, resp.Body.String())
+ }
+ var status, content string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, task).Scan(&status)
+ if status != "queued" {
+ t.Fatalf("run status after the refused edit = %q, want still queued", status)
+ }
+ dbfx.QueryRow(t, `SELECT content FROM comment WHERE id = $1`, comment).Scan(&content)
+ if content != "please look" {
+ t.Fatalf("comment content = %q, want unchanged", content)
+ }
+}
diff --git a/server/internal/handler/guest_plan_test.go b/server/internal/handler/guest_plan_test.go
new file mode 100644
index 0000000000..f4a9e02312
--- /dev/null
+++ b/server/internal/handler/guest_plan_test.go
@@ -0,0 +1,190 @@
+package handler
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/google/uuid"
+
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// useGuestsFeature points the shared handler at a stub that returns decision
+// for the guests paid feature in the test workspace.
+func useGuestsFeature(t *testing.T, decision entitlement.FeatureDecision) {
+ t.Helper()
+ stub := entitlementtest.New()
+ stub.SetFeature(uuid.MustParse(testWorkspaceID), entitlement.FeatureGuests, decision)
+ prior := testHandler.Features
+ testHandler.Features = stub
+ clearFeatureAttempts(t)
+ t.Cleanup(func() {
+ testHandler.Features = prior
+ clearFeatureAttempts(t)
+ })
+}
+
+func wantGuestsLocked(t *testing.T, resp *testutil.Response) {
+ t.Helper()
+ var body struct {
+ Code string `json:"code"`
+ Feature string `json:"feature"`
+ }
+ resp.Want(http.StatusForbidden).JSON(&body)
+ if body.Code != featureLockedCode || body.Feature != string(entitlement.FeatureGuests) {
+ t.Fatalf("locked body = %+v, want feature_locked/guests", body)
+ }
+}
+
+func guestAttempts(t *testing.T) featureAttemptCounts {
+ t.Helper()
+ var c featureAttemptCounts
+ dbfx.QueryRow(t, `
+ SELECT COALESCE(SUM(observed_count), 0), COALESCE(SUM(degraded_count), 0), COALESCE(SUM(enforced_count), 0),
+ COALESCE(MAX(last_operation), '')
+ FROM entitlement_feature_attempt
+ WHERE workspace_id = $1 AND feature = 'guests'`, testWorkspaceID,
+ ).Scan(&c.observed, &c.degraded, &c.enforced, &c.lastOperation)
+ return c
+}
+
+// A plan without guests adds none: no guest invitation, no member made a
+// guest, no project shared with a guest. Existing guests keep working and can
+// be narrowed or made members.
+func TestGuestsFeatureLockedAddsNoGuests(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ f := newGuestFixture(t)
+ addProjectMemberRow(t, f.other, f.guest)
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionEnforce})
+
+ invite := withURLParam(newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members",
+ CreateMemberRequest{Email: f.marker + "[email protected]", Role: "guest", ProjectIDs: []string{f.shared}}), "id", testWorkspaceID)
+ wantGuestsLocked(t, testutil.Call(t, testHandler.CreateInvitation, invite))
+ if n := dbfx.Count(t, `SELECT count(*) FROM workspace_invitation WHERE workspace_id = $1 AND role = 'guest'`, testWorkspaceID); n != 0 {
+ t.Fatalf("guest invitations = %d, want none", n)
+ }
+
+ member := createPlainMember(t, f.marker+"[email protected]")
+ var memberID string
+ dbfx.QueryRow(t, `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, member).Scan(&memberID)
+ demote := withURLParams(newRequest(http.MethodPatch, "/api/workspaces/"+testWorkspaceID+"/members/"+memberID,
+ UpdateMemberRequest{Role: "guest", ProjectIDs: []string{f.shared}}), "id", testWorkspaceID, "memberId", memberID)
+ wantGuestsLocked(t, testutil.Call(t, testHandler.UpdateMember, demote))
+
+ path := "/api/workspaces/" + testWorkspaceID + "/members/" + f.guestMember
+ widen := withURLParams(newRequest(http.MethodPut, path+"/projects",
+ SetMemberProjectsRequest{ProjectIDs: []string{f.shared, f.other, f.secret}}), "id", testWorkspaceID, "memberId", f.guestMember)
+ // The requester is a member of the private project, so sharing it is
+ // allowed by permissions and refused only by the plan.
+ wantGuestsLocked(t, testutil.Call(t, testHandler.SetMemberProjects, widen))
+
+ narrow := withURLParams(newRequest(http.MethodPut, path+"/projects",
+ SetMemberProjectsRequest{ProjectIDs: []string{f.shared}}), "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.SetMemberProjects, narrow).Want(http.StatusOK)
+ if got := guestProjectIDs(t, f.guest); len(got) != 1 || got[0] != f.shared {
+ t.Fatalf("guest projects after narrowing = %v, want only shared", got)
+ }
+
+ // The existing guest still reads its project.
+ rec := guestRequest(t, testHandler.GetIssue, f.guest, http.MethodGet, "/api/issues/"+f.sharedIssue, nil, "id", f.sharedIssue)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("existing guest GET shared issue = %d, want 200", rec.Code)
+ }
+
+ promote := withURLParams(newRequest(http.MethodPatch, path, UpdateMemberRequest{Role: "member"}),
+ "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.UpdateMember, promote).Want(http.StatusOK)
+
+ if got := guestAttempts(t); got.enforced != 3 || got.observed != 0 {
+ t.Fatalf("guest attempts = %+v, want 3 enforced", got)
+ }
+}
+
+// Under observe, guests are added as usual and each addition is recorded.
+func TestGuestsFeatureObservedRecordsAdditions(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ f := newGuestFixture(t)
+ useGuestsFeature(t, entitlement.FeatureDecision{Action: entitlement.ActionObserve})
+
+ invite := withURLParam(newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members",
+ CreateMemberRequest{Email: f.marker + "[email protected]", Role: "guest", ProjectIDs: []string{f.shared}}), "id", testWorkspaceID)
+ testutil.Call(t, testHandler.CreateInvitation, invite).Want(http.StatusCreated)
+
+ // Setting the same projects again adds nothing and records nothing.
+ path := "/api/workspaces/" + testWorkspaceID + "/members/" + f.guestMember
+ same := withURLParams(newRequest(http.MethodPut, path+"/projects",
+ SetMemberProjectsRequest{ProjectIDs: []string{f.shared}}), "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.SetMemberProjects, same).Want(http.StatusOK)
+
+ if got := guestAttempts(t); got.observed != 1 || got.enforced != 0 || got.lastOperation != "invite" {
+ t.Fatalf("guest attempts = %+v, want one observed invite", got)
+ }
+}
+
+// A guest takes no member slot, so a full Free workspace still invites one;
+// turning that guest into a member takes a slot and is refused while full.
+func TestGuestPromotionRespectsMemberLimit(t *testing.T) {
+ workspaceID := memberLimitWorkspace(t, 4)
+ project := dbfx.Project(t, "Member limit guest project", testutil.Cols{"workspace_id": workspaceID})
+ guest := dbfx.User(t, "Member limit guest", "member-limit-guest-"+uuid.NewString()[:8]+"@multica.test")
+ guestMember := dbfx.Member(t, workspaceID, guest, "guest")
+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)
+
+ req := newRequest(http.MethodPost, "/api/workspaces/"+workspaceID+"/members",
+ CreateMemberRequest{Email: "member-limit-guest-invitee-" + uuid.NewString()[:8] + "@multica.test", Role: "guest", ProjectIDs: []string{project}})
+ req.Header.Set("X-Workspace-ID", workspaceID)
+ testutil.Call(t, testHandler.CreateInvitation, withURLParam(req, "id", workspaceID)).Want(http.StatusCreated)
+
+ promote := func() *testutil.Response {
+ req := newRequest(http.MethodPatch, "/api/workspaces/"+workspaceID+"/members/"+guestMember, UpdateMemberRequest{Role: "member"})
+ req.Header.Set("X-Workspace-ID", workspaceID)
+ return testutil.Call(t, testHandler.UpdateMember, withURLParams(req, "id", workspaceID, "memberId", guestMember))
+ }
+ wantMemberLimitReached(t, promote())
+ var role string
+ dbfx.QueryRow(t, `SELECT role FROM member WHERE id = $1`, guestMember).Scan(&role)
+ if role != "guest" {
+ t.Fatalf("role after refused promotion = %q, want guest", role)
+ }
+ if o := memberLimitOverageOf(t, workspaceID); o.enforced != 1 {
+ t.Fatalf("member limit overage = %+v, want one enforced attempt", o)
+ }
+
+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 6)
+ promote().Want(http.StatusOK)
+}
+
+// An attachment outside any issue (docs, chat) is hidden from a guest unless
+// the guest uploaded it.
+func TestGuestSeesOnlyItsOwnAttachmentsOutsideIssues(t *testing.T) {
+ f := newGuestFixture(t)
+ attachment := func(uploader string) string {
+ return dbfx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "uploader_type": "member", "uploader_id": uploader,
+ "filename": "note.png", "url": "https://example.test/" + uuid.NewString() + ".png",
+ "content_type": "image/png", "size_bytes": 1,
+ })
+ }
+ others := attachment(testUserID)
+ own := attachment(f.guest)
+
+ for _, tc := range []struct {
+ name, id string
+ want int
+ }{
+ {"someone else's", others, http.StatusNotFound},
+ {"its own", own, http.StatusOK},
+ } {
+ rec := guestRequest(t, testHandler.GetAttachmentByID, f.guest, http.MethodGet, "/api/attachments/"+tc.id, nil, "id", tc.id)
+ if rec.Code != tc.want {
+ t.Errorf("guest GET %s attachment = %d, want %d", tc.name, rec.Code, tc.want)
+ }
+ }
+ member := createPlainMember(t, f.marker+"[email protected]")
+ rec := guestRequest(t, testHandler.GetAttachmentByID, member, http.MethodGet, "/api/attachments/"+others, nil, "id", others)
+ if rec.Code != http.StatusOK {
+ t.Errorf("member GET attachment = %d, want 200", rec.Code)
+ }
+}
diff --git a/server/internal/handler/guest_test.go b/server/internal/handler/guest_test.go
new file mode 100644
index 0000000000..0eb9f732f1
--- /dev/null
+++ b/server/internal/handler/guest_test.go
@@ -0,0 +1,330 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// guestFixture: a guest of one workspace-visible project (shared), with a
+// second workspace-visible project (other), a private project (secret) and an
+// issue in each plus one issue outside any project.
+type guestFixture struct {
+ guest string
+ shared string
+ other string
+ secret string
+ sharedIssue string
+ otherIssue string
+ secretIssue string
+ looseIssue string
+ guestMember string
+ marker string
+}
+
+func newGuestFixture(t *testing.T) guestFixture {
+ t.Helper()
+ marker := fmt.Sprintf("guest%d", time.Now().UnixNano())
+ f := guestFixture{marker: marker}
+ f.guest = createPlainMember(t, marker+"@multica.test")
+ dbfx.Exec(t, `UPDATE member SET role = 'guest' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, f.guest)
+ dbfx.QueryRow(t, `SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, f.guest).Scan(&f.guestMember)
+ f.shared = dbfx.Project(t, marker+" shared")
+ f.other = dbfx.Project(t, marker+" other")
+ f.secret = dbfx.Project(t, marker+" secret", testutil.Cols{"visibility": projectaccess.VisibilityPrivate})
+ addProjectMemberRow(t, f.shared, f.guest)
+ addProjectMemberRow(t, f.secret, testUserID)
+ base := 700000 + int(time.Now().UnixNano()%100000)*4
+ f.sharedIssue = dbfx.Issue(t, marker+" shared issue", testutil.Cols{"project_id": f.shared, "number": base})
+ f.otherIssue = dbfx.Issue(t, marker+" other issue", testutil.Cols{"project_id": f.other, "number": base + 1})
+ f.secretIssue = dbfx.Issue(t, marker+" secret issue", testutil.Cols{"project_id": f.secret, "number": base + 2})
+ f.looseIssue = dbfx.Issue(t, marker+" loose issue", testutil.Cols{"number": base + 3})
+ return f
+}
+
+// guestRequest runs handler behind the workspace middleware, as the router
+// does, so the guest route allowlist applies.
+func guestRequest(t *testing.T, handler http.HandlerFunc, userID, method, path string, body any, params ...string) *testutil.Response {
+ t.Helper()
+ req := asUser(newRequest(method, path, body), userID)
+ if len(params) > 0 {
+ req = withURLParams(req, params...)
+ }
+ return testutil.Call(t, inboxWorkspaceHandler(handler), req)
+}
+
+func TestGuestSeesOnlyItsProjects(t *testing.T) {
+ f := newGuestFixture(t)
+
+ for _, tc := range []struct {
+ name string
+ issue string
+ want int
+ }{
+ {"issue in its project", f.sharedIssue, http.StatusOK},
+ {"issue in another workspace project", f.otherIssue, http.StatusNotFound},
+ {"issue in a private project", f.secretIssue, http.StatusNotFound},
+ {"issue outside any project", f.looseIssue, http.StatusNotFound},
+ } {
+ rec := guestRequest(t, testHandler.GetIssue, f.guest, http.MethodGet, "/api/issues/"+tc.issue, nil, "id", tc.issue)
+ if rec.Code != tc.want {
+ t.Errorf("%s: GET = %d, want %d", tc.name, rec.Code, tc.want)
+ }
+ }
+
+ var issues struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ rec := guestRequest(t, testHandler.ListIssues, f.guest, http.MethodGet, "/api/issues?limit=200", nil)
+ rec.Want(http.StatusOK).JSON(&issues)
+ for _, is := range issues.Issues {
+ if is.ProjectID == nil || *is.ProjectID != f.shared {
+ t.Errorf("guest list contains issue %s outside its project", is.ID)
+ }
+ }
+ if len(issues.Issues) == 0 {
+ t.Error("guest list is empty, want the shared issue")
+ }
+
+ var projects struct {
+ Projects []ProjectResponse `json:"projects"`
+ }
+ rec = guestRequest(t, testHandler.ListProjects, f.guest, http.MethodGet, "/api/projects", nil)
+ rec.Want(http.StatusOK).JSON(&projects)
+ if len(projects.Projects) != 1 || projects.Projects[0].ID != f.shared {
+ ids := []string{}
+ for _, p := range projects.Projects {
+ ids = append(ids, p.ID)
+ }
+ t.Errorf("guest projects = %v, want only %s", ids, f.shared)
+ }
+
+ // A regular member still sees the workspace project and the loose issue.
+ member := createPlainMember(t, f.marker+"[email protected]")
+ rec = guestRequest(t, testHandler.GetIssue, member, http.MethodGet, "/api/issues/"+f.looseIssue, nil, "id", f.looseIssue)
+ if rec.Code != http.StatusOK {
+ t.Errorf("member GET loose issue = %d, want 200", rec.Code)
+ }
+}
+
+func TestGuestRoutesAreDenyByDefault(t *testing.T) {
+ f := newGuestFixture(t)
+ ok := func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }
+
+ for _, tc := range []struct {
+ method, path string
+ want int
+ }{
+ {http.MethodGet, "/api/issues/" + f.sharedIssue, http.StatusNoContent},
+ {http.MethodPost, "/api/issues/" + f.sharedIssue + "/comments", http.StatusNoContent},
+ {http.MethodGet, "/api/projects", http.StatusNoContent},
+ {http.MethodPut, "/api/issues/" + f.sharedIssue, http.StatusForbidden},
+ {http.MethodPost, "/api/issues", http.StatusForbidden},
+ {http.MethodPost, "/api/projects", http.StatusForbidden},
+ {http.MethodGet, "/api/autopilots", http.StatusForbidden},
+ {http.MethodGet, "/api/runtimes/" + f.sharedIssue, http.StatusForbidden},
+ {http.MethodPost, "/api/chat/sessions", http.StatusForbidden},
+ } {
+ rec := guestRequest(t, ok, f.guest, tc.method, tc.path, nil)
+ if rec.Code != tc.want {
+ t.Errorf("%s %s = %d, want %d", tc.method, tc.path, rec.Code, tc.want)
+ }
+ }
+
+ // The shell's background reads come back empty rather than refused, and
+ // never reach the handler.
+ for path, want := range map[string]string{
+ "/api/runtimes": `[]`,
+ "/api/chat/pending-tasks": `{"tasks":[]}`,
+ "/api/issue-views": `[]`,
+ "/api/project-folders": `{"folders":[],"filed":[]}`,
+ } {
+ rec := guestRequest(t, ok, f.guest, http.MethodGet, path, nil)
+ if rec.Code != http.StatusOK || rec.Body.String() != want {
+ t.Errorf("GET %s = %d %s, want 200 %s", path, rec.Code, rec.Body.String(), want)
+ }
+ }
+}
+
+func TestGuestCannotRunAgents(t *testing.T) {
+ f := newGuestFixture(t)
+ ctx := context.Background()
+ agentID := dbfx.Agent(t, f.marker+" agent", "", testutil.Cols{"owner_id": f.guest})
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if testHandler.canInvokeAgent(ctx, agent, "member", f.guest, f.guest, testWorkspaceID) {
+ t.Error("a guest may invoke the agent it owns, want denied")
+ }
+
+ mention := fmt.Sprintf("[@a](mention://agent/%s) look", agentID)
+ rec := guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost,
+ "/api/issues/"+f.sharedIssue+"/comments", CreateCommentRequest{Content: mention}, "id", f.sharedIssue)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("guest comment mentioning an agent = %d, want 403: %s", rec.Code, rec.Body.String())
+ }
+ rec = guestRequest(t, testHandler.CreateComment, f.guest, http.MethodPost,
+ "/api/issues/"+f.sharedIssue+"/comments", CreateCommentRequest{Content: "plain comment"}, "id", f.sharedIssue)
+ if rec.Code != http.StatusCreated {
+ t.Errorf("guest plain comment = %d, want 201: %s", rec.Code, rec.Body.String())
+ }
+
+ var agents []AgentResponse
+ rec = guestRequest(t, testHandler.ListAgents, f.guest, http.MethodGet, "/api/agents", nil)
+ rec.Want(http.StatusOK).JSON(&agents)
+ for _, a := range agents {
+ if a.Instructions != "" || a.RuntimeID != "" || a.Description != "" {
+ t.Errorf("guest sees agent %s details: %+v", a.ID, a)
+ }
+ }
+}
+
+func TestGuestInvitationAddsProjects(t *testing.T) {
+ clearInvitationsForTestWorkspace(t)
+ f := newGuestFixture(t)
+ email := f.marker + "[email protected]"
+ invitee := dbfx.User(t, "Guest Invitee", email)
+ dbfx.Cleanup(t, `DELETE FROM member WHERE user_id = $1`, invitee)
+
+ req := withURLParam(newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members",
+ CreateMemberRequest{Email: email, Role: "guest"}), "id", testWorkspaceID)
+ testutil.Call(t, testHandler.CreateInvitation, req).Want(http.StatusBadRequest)
+
+ // An admin outside the private project cannot share it.
+ admin := createWorkspaceAdmin(t, f.marker+"[email protected]")
+ req = withURLParam(asUser(newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members",
+ CreateMemberRequest{Email: email, Role: "guest", ProjectIDs: []string{f.secret}}), admin), "id", testWorkspaceID)
+ testutil.Call(t, testHandler.CreateInvitation, req).Want(http.StatusBadRequest)
+
+ var inv InvitationResponse
+ req = withURLParam(newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members",
+ CreateMemberRequest{Email: email, Role: "guest", ProjectIDs: []string{f.shared, f.other}}), "id", testWorkspaceID)
+ testutil.Call(t, testHandler.CreateInvitation, req).Want(http.StatusCreated).JSON(&inv)
+ if inv.Role != "guest" || len(inv.ProjectIDs) != 2 {
+ t.Fatalf("invitation = %+v, want a guest invitation for two projects", inv)
+ }
+
+ req = withURLParam(asUser(newRequest(http.MethodPost, "/api/invitations/"+inv.ID+"/accept", nil), invitee), "id", inv.ID)
+ testutil.Call(t, testHandler.AcceptInvitation, req).Want(http.StatusOK)
+
+ var role string
+ dbfx.QueryRow(t, `SELECT role FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, invitee).Scan(&role)
+ if role != "guest" {
+ t.Fatalf("role = %q, want guest", role)
+ }
+ if got := guestProjectIDs(t, invitee); fmt.Sprint(got) != fmt.Sprint(sorted(f.shared, f.other)) {
+ t.Errorf("guest projects = %v, want shared and other", got)
+ }
+}
+
+func TestGuestPromotionAndDemotion(t *testing.T) {
+ f := newGuestFixture(t)
+ path := "/api/workspaces/" + testWorkspaceID + "/members/" + f.guestMember
+
+ var member MemberResponse
+ req := withURLParams(newRequest(http.MethodPatch, path, UpdateMemberRequest{Role: "member"}), "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.UpdateMember, req).Want(http.StatusOK).JSON(&member)
+ if member.Role != "member" {
+ t.Fatalf("promoted role = %q, want member", member.Role)
+ }
+ rec := guestRequest(t, testHandler.GetIssue, f.guest, http.MethodGet, "/api/issues/"+f.otherIssue, nil, "id", f.otherIssue)
+ if rec.Code != http.StatusOK {
+ t.Errorf("promoted member GET other issue = %d, want 200", rec.Code)
+ }
+
+ req = withURLParams(newRequest(http.MethodPatch, path, UpdateMemberRequest{Role: "guest"}), "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.UpdateMember, req).Want(http.StatusBadRequest)
+
+ addProjectMemberRow(t, f.other, f.guest)
+ req = withURLParams(newRequest(http.MethodPatch, path, UpdateMemberRequest{Role: "guest", ProjectIDs: []string{f.shared}}),
+ "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.UpdateMember, req).Want(http.StatusOK).JSON(&member)
+ if member.Role != "guest" {
+ t.Fatalf("demoted role = %q, want guest", member.Role)
+ }
+ if got := guestProjectIDs(t, f.guest); fmt.Sprint(got) != fmt.Sprint([]string{f.shared}) {
+ t.Errorf("demoted guest projects = %v, want only shared", got)
+ }
+ rec = guestRequest(t, testHandler.GetIssue, f.guest, http.MethodGet, "/api/issues/"+f.otherIssue, nil, "id", f.otherIssue)
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("demoted guest GET other issue = %d, want 404", rec.Code)
+ }
+
+ req = withURLParams(newRequest(http.MethodPut, path+"/projects", SetMemberProjectsRequest{ProjectIDs: []string{f.other}}),
+ "id", testWorkspaceID, "memberId", f.guestMember)
+ testutil.Call(t, testHandler.SetMemberProjects, req).Want(http.StatusOK)
+ if got := guestProjectIDs(t, f.guest); fmt.Sprint(got) != fmt.Sprint([]string{f.other}) {
+ t.Errorf("guest projects after set = %v, want only other", got)
+ }
+
+ var members []MemberWithUserResponse
+ req = withURLParam(newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/members", nil), "id", testWorkspaceID)
+ testutil.Call(t, testHandler.ListMembersWithUser, req).Want(http.StatusOK).JSON(&members)
+ for _, m := range members {
+ if m.UserID == f.guest && fmt.Sprint(m.ProjectIDs) != fmt.Sprint([]string{f.other}) {
+ t.Errorf("members list guest project_ids = %v, want only other", m.ProjectIDs)
+ }
+ }
+}
+
+func TestGuestSeesOnlyGuestsItSharesAProjectWith(t *testing.T) {
+ f := newGuestFixture(t)
+ addGuest := func(email, project string) string {
+ userID := createPlainMember(t, f.marker+email)
+ dbfx.Exec(t, `UPDATE member SET role = 'guest' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID)
+ addProjectMemberRow(t, project, userID)
+ return userID
+ }
+ colleague := addGuest("[email protected]", f.shared)
+ stranger := addGuest("[email protected]", f.other)
+
+ var members []MemberWithUserResponse
+ guestRequest(t, testHandler.ListMembersWithUser, f.guest, http.MethodGet,
+ "/api/workspaces/"+testWorkspaceID+"/members", nil, "id", testWorkspaceID).
+ Want(http.StatusOK).JSON(&members)
+ seen := map[string]bool{}
+ for _, m := range members {
+ seen[m.UserID] = true
+ if len(m.ProjectIDs) > 0 {
+ t.Errorf("guest sees project_ids of %s", m.Name)
+ }
+ }
+ if !seen[f.guest] || !seen[colleague] {
+ t.Errorf("guest misses itself or a guest on its project: %v", seen)
+ }
+ if seen[stranger] {
+ t.Error("guest sees a guest it shares no project with")
+ }
+}
+
+func guestProjectIDs(t *testing.T, userID string) []string {
+ t.Helper()
+ rows, err := testPool.Query(context.Background(),
+ `SELECT project_id::text FROM project_member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var ids []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ return ids
+}
+
+func sorted(ids ...string) []string {
+ sort.Strings(ids)
+ return ids
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 04884681f9..e7cbaae90e 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -40,6 +40,7 @@ import (
"github.com/multica-ai/multica/server/internal/issuestatus"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/realtime"
"github.com/multica-ai/multica/server/internal/seatcapacity"
"github.com/multica-ai/multica/server/internal/service"
@@ -1043,6 +1044,10 @@ func (h *Handler) requireWorkspaceMember(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusNotFound, notFoundMsg)
return db.Member{}, false
}
+ if projectaccess.IsGuestRole(member.Role) && !middleware.GuestMayRequest(r) {
+ middleware.RefuseGuest(w, r)
+ return db.Member{}, false
+ }
return member, true
}
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index 308087edeb..19ee59b5d0 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -15,6 +15,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/seatcapacity"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -28,10 +29,12 @@ type InvitationResponse struct {
InviteeEmail string `json:"invitee_email"`
InviteeUserID *string `json:"invitee_user_id"`
Role string `json:"role"`
- Status string `json:"status"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
- ExpiresAt string `json:"expires_at"`
+ // ProjectIDs are the projects a guest invitee joins on acceptance.
+ ProjectIDs []string `json:"project_ids,omitempty"`
+ Status string `json:"status"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+ ExpiresAt string `json:"expires_at"`
// Enriched fields (present in list responses).
InviterName string `json:"inviter_name,omitempty"`
InviterEmail string `json:"inviter_email,omitempty"`
@@ -46,6 +49,7 @@ func invitationToResponse(inv db.WorkspaceInvitation) InvitationResponse {
InviteeEmail: inv.InviteeEmail,
InviteeUserID: uuidToPtr(inv.InviteeUserID),
Role: inv.Role,
+ ProjectIDs: uuidsToStrings(inv.ProjectIds),
Status: inv.Status,
CreatedAt: timestampToString(inv.CreatedAt),
UpdatedAt: timestampToString(inv.UpdatedAt),
@@ -84,6 +88,17 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "cannot invite as owner")
return
}
+ guest := projectaccess.IsGuestRole(role)
+ var guestProjects []pgtype.UUID
+ var guestAdmission featureAdmission
+ if guest {
+ if guestAdmission, ok = h.requireGuestAddition(w, r, requester.WorkspaceID, "invite"); !ok {
+ return
+ }
+ if guestProjects, ok = h.parseGuestProjectIDs(w, r, requester.WorkspaceID, req.ProjectIDs); !ok {
+ return
+ }
+ }
// Check if the user is already a member.
existingUser, err := h.Queries.GetUserByEmail(r.Context(), email)
@@ -162,7 +177,13 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
invitationID := uuid.New()
expiresAt := time.Now().Add(7 * 24 * time.Hour)
- if err := h.reserveInvitationCapacity(r.Context(), uuid.UUID(requester.WorkspaceID.Bytes), invitationID, expiresAt); err != nil {
+ // A guest takes no seat, so its invitation reserves none.
+ reserveSeat := h.seatCapacityEnabled() && !guest
+ var reserveErr error
+ if reserveSeat {
+ reserveErr = h.reserveInvitationCapacity(r.Context(), uuid.UUID(requester.WorkspaceID.Bytes), invitationID, expiresAt)
+ }
+ if err := reserveErr; err != nil {
if isPersistentSeatCapacityAdmissionRejection(err) {
// Full and overcommitted workspaces cannot admit another member until
// their durable capacity facts change. Charge repeated attempts to the
@@ -183,11 +204,12 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
createParams := db.CreateInvitationParams{
ID: uuidToPG(invitationID), WorkspaceID: requester.WorkspaceID, InviterID: requester.UserID,
InviteeEmail: email, InviteeUserID: inviteeUserID, Role: role,
- ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
+ ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
+ ProjectIds: guestProjects,
}
var inv db.WorkspaceInvitation
var limitAdmission memberLimitAdmission
- if h.seatCapacityEnabled() || memberLimit.active() {
+ if reserveSeat || memberLimit.active() {
tx, txErr := h.TxStarter.Begin(r.Context())
if txErr != nil {
h.compensateCapacityIntent(r.Context(), invitationID)
@@ -203,7 +225,7 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
if err == nil {
inv, err = qtx.CreateInvitation(r.Context(), createParams)
}
- if err == nil && h.seatCapacityEnabled() {
+ if err == nil && reserveSeat {
err = qtx.DeleteSeatCapacityIntentForAction(r.Context(), db.DeleteSeatCapacityIntentForActionParams{
OperationToken: uuidToPG(invitationID), Action: seatcapacity.ActionReserveInvitation,
})
@@ -237,6 +259,7 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
return
}
+ guestAdmission.admitted(r.Context())
slog.Info("invitation created", append(logger.RequestAttrs(r), "invitation_id", uuidToString(inv.ID), "workspace_id", workspaceID, "email", email, "role", role)...)
resp := invitationToResponse(inv)
@@ -300,6 +323,7 @@ func (h *Handler) ListWorkspaceInvitations(w http.ResponseWriter, r *http.Reques
InviteeEmail: row.InviteeEmail,
InviteeUserID: uuidToPtr(row.InviteeUserID),
Role: row.Role,
+ ProjectIDs: uuidsToStrings(row.ProjectIds),
Status: row.Status,
CreatedAt: timestampToString(row.CreatedAt),
UpdatedAt: timestampToString(row.UpdatedAt),
@@ -536,7 +560,8 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
return
}
// The invitation already holds its slot. A refusal leaves it pending, so
- // the invitee can still accept once the workspace upgrades.
+ // the invitee can still accept once the workspace upgrades. A guest takes
+ // neither a member slot nor a seat.
memberLimit, err := h.memberLimitFor(r.Context(), inv.WorkspaceID, inv.Role, true)
if err != nil {
if errors.Is(err, errMemberLimitReached) {
@@ -546,10 +571,24 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to accept invitation")
return
}
- capacityActive, err := h.beginCapacityConsume(r.Context(), uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(user.ID.Bytes))
- if err != nil {
- writeSeatCapacityError(w, err)
- return
+ guest := projectaccess.IsGuestRole(inv.Role)
+ // Accepting adds the guest, so it passes the same gate as inviting one:
+ // an invitation sent during a trial or before guests were switched off
+ // does not admit a guest the workspace can no longer add. A refusal
+ // leaves the invitation pending, as the member limit does above.
+ var guestAdmission featureAdmission
+ if guest {
+ if guestAdmission, ok = h.requireGuestAddition(w, r, inv.WorkspaceID, "accept_invitation"); !ok {
+ return
+ }
+ }
+ capacityActive := false
+ if !guest {
+ capacityActive, err = h.beginCapacityConsume(r.Context(), uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(user.ID.Bytes))
+ if err != nil {
+ writeSeatCapacityError(w, err)
+ return
+ }
}
// Use a transaction: mark accepted + create member atomically.
@@ -596,6 +635,15 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to create membership")
return
}
+ if guest {
+ if _, err := qtx.AddUserToProjects(r.Context(), db.AddUserToProjectsParams{
+ WorkspaceID: accepted.WorkspaceID, UserID: user.ID,
+ ProjectIds: accepted.ProjectIds, AddedBy: accepted.InviterID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create membership")
+ return
+ }
+ }
// Accepting an invite marks the invitee as onboarded. The web /
// desktop workspace layout has a hard onboarded_at gate; without
@@ -624,6 +672,7 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
return
}
limitAdmission.record(r.Context())
+ guestAdmission.admitted(r.Context())
if capacityActive {
h.confirmCapacityIntent(r.Context(), uuid.UUID(accepted.WorkspaceID.Bytes), uuid.UUID(accepted.ID.Bytes), uuid.UUID(member.ID.Bytes))
}
diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.go
index 72c556f861..c5b35e590d 100644
--- a/server/internal/handler/plugin_action.go
+++ b/server/internal/handler/plugin_action.go
@@ -12,6 +12,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -148,9 +149,26 @@ func (h *Handler) pluginSessionCaller(w http.ResponseWriter, r *http.Request, sc
publicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "workspace not found")
return service.PluginActionCaller{}, pluginActor{}, false
}
+ if !refusePluginGuest(w, r, member) {
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
return caller, pluginActor{Type: "member", Member: member}, true
}
+// refusePluginGuest keeps guests (MUL-9420) off the Action API, whichever way
+// the call reached it. A guest is offered no plugin surface or hook, and the
+// API has no notion of its limits: it reads only the projects shared with it
+// and changes no issue field, while plugin endpoints read workspace storage
+// and task transcripts and write issue content. It reports whether the call
+// may proceed.
+func refusePluginGuest(w http.ResponseWriter, r *http.Request, member db.Member) bool {
+ if !projectaccess.IsGuestRole(member.Role) {
+ return true
+ }
+ publicapiv1.WriteProblem(w, r, http.StatusForbidden, "guest_not_allowed", "guests cannot use Plugins")
+ return false
+}
+
// pluginTokenCaller is the hook path: a plugin's own server calling in.
//
// A callback token is scoped to one INVOCATION, lives for minutes, and carries
@@ -207,6 +225,11 @@ func (h *Handler) pluginTokenCaller(w http.ResponseWriter, r *http.Request, toke
publicapiv1.WriteProblem(w, r, http.StatusForbidden, "actor_membership_revoked", "the user this callback acts for is no longer a member")
return service.PluginActionCaller{}, pluginActor{}, false
}
+ // Checked today, like membership: a member made a guest after the
+ // hook went out loses the callback with the rest of its access.
+ if !refusePluginGuest(w, r, member) {
+ return service.PluginActionCaller{}, pluginActor{}, false
+ }
actor = pluginActor{Type: "member", Member: member}
}
return caller, actor, true
@@ -218,7 +241,7 @@ func (h *Handler) pluginTokenCaller(w http.ResponseWriter, r *http.Request, toke
// member of it" is exactly the reach the user already has. An issue outside it
// is a 404 for the same reason it is on the ordinary endpoint: a plugin must
// not be able to confirm that an id it cannot read exists.
-func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, caller service.PluginActionCaller, issueID string) (db.Issue, bool) {
+func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, caller service.PluginActionCaller, actor pluginActor, issueID string) (db.Issue, bool) {
if issueID == "" {
publicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "issue not found")
return db.Issue{}, false
@@ -241,6 +264,20 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, cal
publicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "issue not found")
return db.Issue{}, false
}
+ // A call that acts as a person reaches only the projects that person can
+ // see (MUL-8472): an issue in a private project they are not a member of
+ // is as missing here as on the ordinary endpoint.
+ if actor.isMember() {
+ hidden, err := projectaccess.ForMember(r.Context(), h.Queries, actor.Member)
+ if err != nil {
+ publicapiv1.WriteProblem(w, r, http.StatusInternalServerError, "internal_error", "failed to resolve project access")
+ return db.Issue{}, false
+ }
+ if !hidden.CanSeeProject(issue.ProjectID) {
+ publicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "issue not found")
+ return db.Issue{}, false
+ }
+ }
return issue, true
}
@@ -292,7 +329,7 @@ func (h *Handler) GetPluginContext(w http.ResponseWriter, r *http.Request) {
var issue *db.Issue
if issueID := r.URL.Query().Get("issue_id"); issueID != "" {
- loaded, ok := h.pluginIssueForUser(w, r, caller, issueID)
+ loaded, ok := h.pluginIssueForUser(w, r, caller, actor, issueID)
if !ok {
return
}
@@ -328,11 +365,11 @@ func publicPluginContext(context service.PluginContext) publicapiv1.Context {
// GetPluginIssue — GET /v1/issues/{issue_ref}
func (h *Handler) GetPluginIssue(w http.ResponseWriter, r *http.Request) {
- caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesRead)
+ caller, actor, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesRead)
if !ok {
return
}
- issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "issue_ref"))
+ issue, ok := h.pluginIssueForUser(w, r, caller, actor, chi.URLParam(r, "issue_ref"))
if !ok {
return
}
@@ -349,11 +386,11 @@ func (h *Handler) GetPluginIssue(w http.ResponseWriter, r *http.Request) {
// drifting copy of them. Widening this set later is additive; getting the side
// effects wrong now is not.
func (h *Handler) PatchPluginIssue(w http.ResponseWriter, r *http.Request) {
- caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesWrite)
+ caller, actor, ok := h.pluginCaller(w, r, plugincontract.ScopeIssuesWrite)
if !ok {
return
}
- issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "issue_ref"))
+ issue, ok := h.pluginIssueForUser(w, r, caller, actor, chi.URLParam(r, "issue_ref"))
if !ok {
return
}
@@ -465,6 +502,22 @@ func (h *Handler) ListPluginTaskMessages(w http.ResponseWriter, r *http.Request)
publicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "task not found")
return
}
+ // A person reads the transcript of a run only about projects they can
+ // see, as pluginIssueForUser does for issues.
+ if actor.isMember() {
+ hidden, err := projectaccess.ForMember(r.Context(), h.Queries, actor.Member)
+ if err == nil && !hidden.Empty() {
+ var projects []pgtype.UUID
+ if projects, err = projectaccess.TaskProjects(r.Context(), h.Queries, task); err == nil && !hidden.CanSeeProjects(projects) {
+ publicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "task not found")
+ return
+ }
+ }
+ if err != nil {
+ publicapiv1.WriteProblem(w, r, http.StatusInternalServerError, "internal_error", "failed to resolve project access")
+ return
+ }
+ }
var messages []db.TaskMessage
if sinceStr := r.URL.Query().Get("since"); sinceStr != "" {
@@ -572,11 +625,11 @@ func (h *Handler) pluginIssuePayload(r *http.Request, caller service.PluginActio
// ListPluginComments — GET /v1/issues/{issue_ref}/comments
func (h *Handler) ListPluginComments(w http.ResponseWriter, r *http.Request) {
- caller, _, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsRead)
+ caller, actor, ok := h.pluginCaller(w, r, plugincontract.ScopeCommentsRead)
if !ok {
return
}
- issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "issue_ref"))
+ issue, ok := h.pluginIssueForUser(w, r, caller, actor, chi.URLParam(r, "issue_ref"))
if !ok {
return
}
@@ -627,7 +680,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- issue, ok := h.pluginIssueForUser(w, r, caller, chi.URLParam(r, "issue_ref"))
+ issue, ok := h.pluginIssueForUser(w, r, caller, actor, chi.URLParam(r, "issue_ref"))
if !ok {
return
}
diff --git a/server/internal/handler/plugin_hook.go b/server/internal/handler/plugin_hook.go
index 5d9bef071a..002aa06dbb 100644
--- a/server/internal/handler/plugin_hook.go
+++ b/server/internal/handler/plugin_hook.go
@@ -75,7 +75,7 @@ func (h *Handler) InvokePluginHook(w http.ResponseWriter, r *http.Request) {
Input: rawOrNil(req.Input),
}
if req.IssueID != "" {
- issue, ok := h.pluginIssueForUser(w, r, caller, req.IssueID)
+ issue, ok := h.pluginIssueForUser(w, r, caller, actor, req.IssueID)
if !ok {
return
}
diff --git a/server/internal/handler/project.go b/server/internal/handler/project.go
index 5d0ce966b8..54f0583fc9 100644
--- a/server/internal/handler/project.go
+++ b/server/internal/handler/project.go
@@ -500,6 +500,11 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {
return
}
}
+ // A new project shared with a guest is a guest addition (MUL-9420).
+ guestAdmission, ok := h.requireGuestProjectAddition(w, r, wsUUID, pgtype.UUID{}, privateMemberIDs)
+ if !ok {
+ return
+ }
actorType, actorID := h.resolveActor(r, userID, workspaceID)
creatorID, ok := parseUUIDOrBadRequest(w, actorID, "creator_id")
@@ -609,6 +614,7 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {
return
}
admission.admitted(r.Context())
+ guestAdmission.admitted(r.Context())
resourceResp := make([]ProjectResourceResponse, len(resourceRows))
for i, row := range resourceRows {
@@ -773,11 +779,18 @@ func (h *Handler) UpdateProject(w http.ResponseWriter, r *http.Request) {
return
}
}
+ // Adding a guest to the member list (or naming one lead of a private
+ // project) shares the project with it (MUL-9420).
+ guestAdmission, ok := h.requireGuestProjectAddition(w, r, prevProject.WorkspaceID, prevProject.ID, access.addIDs)
+ if !ok {
+ return
+ }
project, ok := h.writeProjectUpdate(w, r, params, access, userID)
if !ok {
return
}
admission.admitted(r.Context())
+ guestAdmission.admitted(r.Context())
resp := projectToResponse(project)
h.fillProjectIssueStats(r.Context(), &resp, project)
resp.ResourceCount = h.loadProjectResourceCount(r.Context(), project.ID)
diff --git a/server/internal/handler/project_access.go b/server/internal/handler/project_access.go
index a35f21b9f3..eafe2da942 100644
--- a/server/internal/handler/project_access.go
+++ b/server/internal/handler/project_access.go
@@ -34,7 +34,7 @@ func (h *Handler) hiddenProjects(r *http.Request, workspaceID string) (projectac
return projectaccess.ForPrincipals(ctx, h.Queries, wsUUID)
}
if m, ok := ctxMember(ctx); ok && m.WorkspaceID == wsUUID && m.UserID == userUUID {
- return projectaccess.ForMember(ctx, h.Queries, wsUUID, userUUID)
+ return projectaccess.ForMember(ctx, h.Queries, m)
}
return projectaccess.ForPrincipals(ctx, h.Queries, wsUUID, userUUID)
}
@@ -86,7 +86,8 @@ func (h *Handler) requestHiddenProjects(w http.ResponseWriter, r *http.Request,
// message they already use for a missing object: a hidden object must be
// indistinguishable from one that does not exist, so this never answers 403.
func (h *Handler) requireProjectVisible(w http.ResponseWriter, r *http.Request, workspaceID string, projectID pgtype.UUID, status int, notFoundMsg string) bool {
- if !projectID.Valid {
+ // Only a guest is kept from objects outside any project.
+ if m, ok := ctxMember(r.Context()); !projectID.Valid && ok && !projectaccess.IsGuestRole(m.Role) {
return true
}
hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
@@ -291,6 +292,15 @@ func (h *Handler) attachmentInHiddenProject(ctx context.Context, hidden projecta
// issue) in a project the caller cannot see.
func (h *Handler) requireAttachmentVisible(w http.ResponseWriter, r *http.Request, workspaceID string, att db.Attachment) bool {
if !att.IssueID.Valid && !att.CommentID.Valid {
+ // Outside any issue (docs, chat): a guest (MUL-9420) sees nothing
+ // outside its projects, except what it uploaded itself, such as an
+ // image in a comment it has not posted yet.
+ userID := requestUserID(r)
+ ownUpload := att.UploaderType == "member" && uuidToString(att.UploaderID) == userID
+ if !ownUpload && h.isGuest(r, workspaceID, userID) {
+ writeError(w, http.StatusNotFound, "attachment not found")
+ return false
+ }
return true
}
hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
@@ -398,11 +408,14 @@ func (h *Handler) chatRunProjectID(ctx context.Context, cs db.ChatSession, task
}
// hiddenProjectPredicate is the dynamic-SQL twin of the sqlc
-// hidden_project_ids filter: rows outside any project always pass.
+// hidden_project_ids filter: rows outside any project pass unless the set
+// holds projectaccess.NoProject.
func hiddenProjectPredicate(column, param string) string {
- return "(" + column + " IS NULL OR NOT (" + column + " = ANY(" + param + "::uuid[])))"
+ return "(NOT (COALESCE(" + column + ", '" + noProjectSQL + "'::uuid) = ANY(" + param + "::uuid[])))"
}
+const noProjectSQL = "00000000-0000-0000-0000-000000000000"
+
// filterVisibleIssues drops issues in hidden projects from an unpaginated list.
func filterVisibleIssues(hidden projectaccess.Hidden, issues []db.Issue) []db.Issue {
if hidden.Empty() {
diff --git a/server/internal/handler/project_member.go b/server/internal/handler/project_member.go
index f397bf2582..bb113df73d 100644
--- a/server/internal/handler/project_member.go
+++ b/server/internal/handler/project_member.go
@@ -539,6 +539,12 @@ func (h *Handler) AddProjectMembers(w http.ResponseWriter, r *http.Request) {
if !h.requireProjectAccessManager(w, r, member, project, "only workspace admins and the member who manages this project's access can add members") {
return
}
+ // Sharing the project with a guest who is not in it yet is a guest
+ // addition (MUL-9420), whatever the project's visibility.
+ guestAdmission, ok := h.requireGuestProjectAddition(w, r, project.WorkspaceID, project.ID, ids)
+ if !ok {
+ return
+ }
var admission featureAdmission
if projectVisibilityOrDefault(project.Visibility) == projectaccess.VisibilityPrivate {
grows, err := h.projectMembersGrow(r, project, ids)
@@ -581,6 +587,7 @@ func (h *Handler) AddProjectMembers(w http.ResponseWriter, r *http.Request) {
return
}
admission.admitted(r.Context())
+ guestAdmission.admitted(r.Context())
h.publishProjectMembersChanged(project, member.UserID)
h.ListProjectMembers(w, r)
}
diff --git a/server/internal/handler/search_index.go b/server/internal/handler/search_index.go
index 1ff46fffac..e7f54d4822 100644
--- a/server/internal/handler/search_index.go
+++ b/server/internal/handler/search_index.go
@@ -21,6 +21,7 @@ import (
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -479,19 +480,29 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)
limit = min(req.Limit, searchIndexChangesMaxLimit)
}
+ // Agents and other non-user callers have no per-user marker to check.
+ viewer, _ := util.ParseUUID(requestUserID(r))
var (
- pruned bool
- target = cur.Target
- changes []db.ListSearchIndexChangesRow
- issues []db.Issue
- comments []db.ListSearchIndexCommentsByIDsRow
- projects []db.Project
+ pruned bool
+ accessChanged bool
+ target = cur.Target
+ changes []db.ListSearchIndexChangesRow
+ issues []db.Issue
+ comments []db.ListSearchIndexCommentsByIDsRow
+ projects []db.Project
)
err = h.runSearchIndexRead(ctx, func(q *db.Queries) error {
var err error
if pruned, err = q.SearchIndexSinceIsPruned(ctx, cur.Since); err != nil || pruned {
return err
}
+ if viewer.Valid {
+ if accessChanged, err = q.SearchAccessChangedAfter(ctx, db.SearchAccessChangedAfterParams{
+ WorkspaceID: wsUUID, UserID: viewer, SinceSnapshot: cur.Since,
+ }); err != nil || accessChanged {
+ return err
+ }
+ }
if target == "" {
if target, err = q.GetSearchIndexCurrentSnapshot(ctx); err != nil {
return err
@@ -560,6 +571,14 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusGone, "search index cursor expired; rebuild the local index")
return
}
+ if accessChanged {
+ // The caller's access changed after this copy's snapshot (made a
+ // guest or a member, or a guest gained or lost a project). The
+ // content it gained or lost was not rewritten, so no change would
+ // deliver or remove it; only a rebuild does.
+ writeError(w, http.StatusGone, "search index access changed; rebuild the local index")
+ return
+ }
// Entities in a project the caller cannot see are reported as deleted, so
// a client that synced them before losing access drops its copy.
hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))
diff --git a/server/internal/handler/search_index_test.go b/server/internal/handler/search_index_test.go
index 9041c69b18..cc400de00d 100644
--- a/server/internal/handler/search_index_test.go
+++ b/server/internal/handler/search_index_test.go
@@ -345,6 +345,9 @@ func TestDeleteWorkspace_ClearsSearchIndexChanges(t *testing.T) {
if n := dbfx.Count(t, `SELECT count(*) FROM search_index_change WHERE workspace_id = $1`, wsID); n == 0 {
t.Fatal("writes should have logged search index changes")
}
+ if _, err := testPool.Exec(ctx, `INSERT INTO member_search_access (workspace_id, user_id, changed_xid) VALUES ($1, $2, pg_current_xact_id())`, wsID, testUserID); err != nil {
+ t.Fatalf("record search access marker: %v", err)
+ }
w := httptest.NewRecorder()
testHandler.DeleteWorkspace(w, withURLParam(newRequest(http.MethodDelete, "/api/workspaces/"+wsID, nil), "id", wsID))
@@ -354,6 +357,9 @@ func TestDeleteWorkspace_ClearsSearchIndexChanges(t *testing.T) {
if n := dbfx.Count(t, `SELECT count(*) FROM search_index_change WHERE workspace_id = $1`, wsID); n != 0 {
t.Fatalf("workspace teardown left %d search index change rows", n)
}
+ if n := dbfx.Count(t, `SELECT count(*) FROM member_search_access WHERE workspace_id = $1`, wsID); n != 0 {
+ t.Fatalf("workspace teardown left %d search access markers", n)
+ }
}
func TestRequireLocalSearchIndexHonorsKillSwitch(t *testing.T) {
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 71c7d4c25f..3357b4d8c6 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -20,6 +20,7 @@ import (
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -574,6 +575,9 @@ type MemberWithUserResponse struct {
Name string `json:"name"`
Email string `json:"email"`
AvatarURL *string `json:"avatar_url"`
+ // ProjectIDs lists a guest's projects. Omitted for other roles, and for
+ // guests when a guest is asking.
+ ProjectIDs []string `json:"project_ids,omitempty"`
}
func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
@@ -589,9 +593,42 @@ func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
return
}
- resp := make([]MemberWithUserResponse, len(members))
- for i, m := range members {
- resp[i] = MemberWithUserResponse{
+ rows, err := h.Queries.ListGuestProjects(r.Context(), wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list members")
+ return
+ }
+ guestProjects := map[[16]byte][]string{}
+ for _, row := range rows {
+ guestProjects[row.UserID.Bytes] = append(guestProjects[row.UserID.Bytes], uuidToString(row.ProjectID))
+ }
+ // A guest sees the members, itself, and only those guests it shares a
+ // project with: guests are often outside people who should not learn of
+ // each other. Nobody's projects are listed to a guest.
+ requester, _ := ctxMember(r.Context())
+ requesterIsGuest := projectaccess.IsGuestRole(requester.Role)
+ visibleGuests := map[[16]byte]bool{requester.UserID.Bytes: true}
+ if requesterIsGuest {
+ mine := map[string]bool{}
+ for _, id := range guestProjects[requester.UserID.Bytes] {
+ mine[id] = true
+ }
+ for userID, ids := range guestProjects {
+ for _, id := range ids {
+ if mine[id] {
+ visibleGuests[userID] = true
+ break
+ }
+ }
+ }
+ }
+ resp := make([]MemberWithUserResponse, 0, len(members))
+ for _, m := range members {
+ guest := projectaccess.IsGuestRole(m.Role)
+ if requesterIsGuest && guest && !visibleGuests[m.UserID.Bytes] {
+ continue
+ }
+ item := MemberWithUserResponse{
ID: uuidToString(m.ID),
WorkspaceID: uuidToString(m.WorkspaceID),
UserID: uuidToString(m.UserID),
@@ -601,6 +638,10 @@ func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
Email: m.UserEmail,
AvatarURL: h.resolveAvatarURLPtr(textToPtr(m.UserAvatarUrl)),
}
+ if guest && !requesterIsGuest {
+ item.ProjectIDs = guestProjects[m.UserID.Bytes]
+ }
+ resp = append(resp, item)
}
writeJSON(w, http.StatusOK, resp)
@@ -609,6 +650,8 @@ func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
type CreateMemberRequest struct {
Email string `json:"email"`
Role string `json:"role"`
+ // ProjectIDs are required for a guest and ignored otherwise.
+ ProjectIDs []string `json:"project_ids,omitempty"`
}
func (h *Handler) memberWithUserResponse(member db.Member, user db.User) MemberWithUserResponse {
@@ -631,7 +674,7 @@ func normalizeMemberRole(role string) (string, bool) {
role = strings.TrimSpace(role)
switch role {
- case "owner", "admin", "member":
+ case "owner", "admin", "member", projectaccess.RoleGuest:
return role, true
default:
return "", false
@@ -640,6 +683,8 @@ func normalizeMemberRole(role string) (string, bool) {
type UpdateMemberRequest struct {
Role string `json:"role"`
+ // ProjectIDs are required when the member becomes a guest.
+ ProjectIDs []string `json:"project_ids,omitempty"`
}
func (h *Handler) UpdateMember(w http.ResponseWriter, r *http.Request) {
@@ -693,12 +738,33 @@ func (h *Handler) UpdateMember(w http.ResponseWriter, r *http.Request) {
}
}
- updatedMember, err := h.Queries.UpdateMemberRole(r.Context(), db.UpdateMemberRoleParams{
- ID: target.ID,
- Role: role,
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to update member")
+ wasGuest := projectaccess.IsGuestRole(target.Role)
+ toGuest := projectaccess.IsGuestRole(role)
+ var updatedMember db.Member
+ var guestProjects []pgtype.UUID
+ switch {
+ case toGuest && !wasGuest:
+ var admission featureAdmission
+ if admission, ok = h.requireGuestAddition(w, r, target.WorkspaceID, "make_guest"); !ok {
+ return
+ }
+ if guestProjects, ok = h.parseGuestProjectIDs(w, r, target.WorkspaceID, req.ProjectIDs); !ok {
+ return
+ }
+ updatedMember, ok = h.demoteMemberToGuest(w, r, requester, target, guestProjects)
+ if ok {
+ admission.admitted(r.Context())
+ }
+ case wasGuest && !toGuest:
+ updatedMember, ok = h.promoteGuest(w, r, target, role)
+ default:
+ updatedMember, err = h.updateMemberRoleFrom(r.Context(), target, role)
+ if err != nil {
+ writeMemberUpdateError(w, err)
+ return
+ }
+ }
+ if !ok {
return
}
@@ -710,12 +776,40 @@ func (h *Handler) UpdateMember(w http.ResponseWriter, r *http.Request) {
return
}
+ resp := h.memberWithUserResponse(updatedMember, user)
+ if toGuest {
+ resp.ProjectIDs = uuidsToStrings(guestProjects)
+ }
userID := requestUserID(r)
h.publish(protocol.EventMemberUpdated, uuidToString(requester.WorkspaceID), "member", userID, map[string]any{
- "member": h.memberWithUserResponse(updatedMember, user),
+ "member": resp,
})
- writeJSON(w, http.StatusOK, h.memberWithUserResponse(updatedMember, user))
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// updateMemberRoleFrom changes a role that neither starts nor ends as guest.
+// The row is locked and must still hold target's role: a concurrent change
+// (say the member became a guest and gave up its seat) is never overwritten
+// by a request decided on the role it had before.
+func (h *Handler) updateMemberRoleFrom(ctx context.Context, target db.Member, role string) (db.Member, error) {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.Member{}, err
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ if _, err := lockMemberRole(ctx, qtx, target.ID, target.Role); err != nil {
+ return db.Member{}, err
+ }
+ updated, err := qtx.UpdateMemberRole(ctx, db.UpdateMemberRoleParams{ID: target.ID, Role: role})
+ if err != nil {
+ return db.Member{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.Member{}, err
+ }
+ return updated, nil
}
func (h *Handler) DeleteMember(w http.ResponseWriter, r *http.Request) {
@@ -1357,6 +1451,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
name: "delete search index changes",
run: func() error { return qtx.DeleteWorkspaceSearchIndexChanges(ctx, requester.WorkspaceID) },
},
+ {
+ name: "delete search access markers",
+ run: func() error { return qtx.DeleteWorkspaceMemberSearchAccess(ctx, requester.WorkspaceID) },
+ },
// Keep source-context object intents after the workspace row is gone.
// They are the durable retry ledger for an upload that began before the
// workspace lock but completed after this transaction's immediate object
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 4c70162137..cb55d95a1b 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -109,6 +109,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"lark_user_binding": workspaceDelete,
"maintenance_job": workspaceDeleteKeep, // Global maintenance audit history, not workspace-owned.
"member": workspaceDelete,
+ "member_search_access": workspaceDelete,
"member_delegation_day": workspaceDeleteKeep, // user-scoped telemetry ledger, no workspace_id
"agent_mcp_server": workspaceDelete,
"workspace_mcp_server": workspaceDelete,
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index 087a193e82..f5af1db9c9 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -7,6 +7,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -43,7 +44,23 @@ import (
// the requester (the admin doing the kick); for LeaveWorkspace it's the leaver
// themselves.
func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID, memberID, archivedBy pgtype.UUID) (revocationResult, error) {
+ return h.revokeMember(ctx, workspaceID, userID, memberID, archivedBy, nil, "")
+}
+
+// revokeAndDemoteToGuest is revokeAndRemoveMember for a member who becomes a
+// guest (MUL-9420): the same revocation, since a guest runs no agents, holds
+// no seat and sees only its projects, but the member row stays, with the
+// guest role and exactly guestProjects as its projects. fromRole is the role
+// the demotion was decided on: if the member no longer has it when the
+// transaction locks the row, nothing changes and errMemberRoleChanged is
+// returned.
+func (h *Handler) revokeAndDemoteToGuest(ctx context.Context, workspaceID, userID, memberID, archivedBy pgtype.UUID, guestProjects []pgtype.UUID, fromRole string) (revocationResult, error) {
+ return h.revokeMember(ctx, workspaceID, userID, memberID, archivedBy, guestProjects, fromRole)
+}
+
+func (h *Handler) revokeMember(ctx context.Context, workspaceID, userID, memberID, archivedBy pgtype.UUID, guestProjects []pgtype.UUID, fromRole string) (revocationResult, error) {
var empty revocationResult
+ demote := guestProjects != nil
tx, err := h.TxStarter.Begin(ctx)
if err != nil {
@@ -66,6 +83,14 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
return empty, err
}
+ // A demotion re-checks the role under the row lock: a concurrent role
+ // change that committed first wins, and this one is refused.
+ if demote {
+ if _, err := lockMemberRole(ctx, qtx, memberID, fromRole); err != nil {
+ return empty, err
+ }
+ }
+
if _, err := qtx.LockRuntimeShareMemberRemoval(ctx, db.LockRuntimeShareMemberRemovalParams{
WorkspaceID: workspaceID, UserID: userID,
}); err != nil {
@@ -273,8 +298,20 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
}
// No FK cascade (repo rule): a departing member leaves every private
- // project in the workspace and stops watching every project.
- if err := qtx.DeleteProjectMembersByUser(ctx, db.DeleteProjectMembersByUserParams{
+ // project in the workspace and stops watching every project. A new guest
+ // keeps exactly its guest projects.
+ if demote {
+ if _, err := qtx.RemoveUserFromProjectsExcept(ctx, db.RemoveUserFromProjectsExceptParams{
+ WorkspaceID: workspaceID, UserID: userID, KeepProjectIds: guestProjects,
+ }); err != nil {
+ return empty, err
+ }
+ if _, err := qtx.AddUserToProjects(ctx, db.AddUserToProjectsParams{
+ WorkspaceID: workspaceID, UserID: userID, ProjectIds: guestProjects, AddedBy: archivedBy,
+ }); err != nil {
+ return empty, err
+ }
+ } else if err := qtx.DeleteProjectMembersByUser(ctx, db.DeleteProjectMembersByUserParams{
WorkspaceID: workspaceID, UserID: userID,
}); err != nil {
return empty, err
@@ -284,7 +321,16 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
}); err != nil {
return empty, err
}
- if err := qtx.DeleteMember(ctx, memberID); err != nil {
+ if demote {
+ if _, err := qtx.UpdateMemberRole(ctx, db.UpdateMemberRoleParams{ID: memberID, Role: projectaccess.RoleGuest}); err != nil {
+ return empty, err
+ }
+ // The new guest no longer sees most of what its local search copy
+ // holds; make that copy rebuild.
+ if err := markSearchAccessChanged(ctx, qtx, workspaceID, userID); err != nil {
+ return empty, err
+ }
+ } else if err := qtx.DeleteMember(ctx, memberID); err != nil {
return empty, err
}
diff --git a/server/internal/middleware/guest.go b/server/internal/middleware/guest.go
new file mode 100644
index 0000000000..4af1f5e5fc
--- /dev/null
+++ b/server/internal/middleware/guest.go
@@ -0,0 +1,197 @@
+package middleware
+
+import (
+ "net/http"
+ "strings"
+)
+
+// Guests (MUL-9420) are deny-by-default: a workspace route answers a guest
+// only when it is listed here. Everything a listed route returns is still
+// narrowed to the guest's projects by projectaccess, so this list decides
+// which kinds of thing a guest may touch, not which rows.
+//
+// A pattern is "METHOD /path", where "*" matches exactly one path segment.
+var guestRoutes = compileGuestRoutes([]string{
+ // The workspace shell: its record, its people (names for mentions and
+ // assignees), and leaving it.
+ "GET /api/workspaces/*",
+ "GET /api/workspaces/*/members",
+ // Which paid features the plan includes: not sensitive, and shared
+ // components read it to render locked states.
+ "GET /api/workspaces/*/features",
+ "POST /api/workspaces/*/leave",
+
+ // Reading issues in the guest's projects.
+ "GET /api/issues",
+ "POST /api/issues/query",
+ "POST /api/issues/table/groups",
+ "POST /api/issues/table/rows",
+ "POST /api/issues/table/facets",
+ "GET /api/issues/search",
+ "GET /api/issues/child-progress",
+ "GET /api/issues/children",
+ "GET /api/issues/grouped",
+ "GET /api/issues/unread",
+ "GET /api/issues/subscribed",
+ "GET /api/issues/pull-requests",
+ "GET /api/issues/*",
+ "GET /api/issues/*/comments",
+ "GET /api/issues/*/timeline",
+ "GET /api/issues/*/subscribers",
+ "GET /api/issues/*/attachments",
+ "GET /api/issues/*/children",
+ "GET /api/issues/*/labels",
+ "GET /api/issues/*/metadata",
+ "GET /api/issues/*/pull-requests",
+ "GET /api/issues/*/active-task",
+ "GET /api/issues/*/duplicates",
+
+ // Commenting, reacting and following.
+ "POST /api/issues/*/comments",
+ "POST /api/issues/*/reactions",
+ "DELETE /api/issues/*/reactions",
+ "POST /api/issues/*/subscribe",
+ "POST /api/issues/*/unsubscribe",
+ "POST /api/issues/*/read",
+ "POST /api/issues/*/unread",
+ "PUT /api/comments/*",
+ "DELETE /api/comments/*",
+ // The same delete under the path clients use when they promise to keep
+ // the replies (#8296); the handler still allows only the author.
+ "DELETE /api/comments/*/keep-replies",
+ "POST /api/comments/*/reactions",
+ "DELETE /api/comments/*/reactions",
+
+ // Projects shared with the guest.
+ "GET /api/projects",
+ "GET /api/projects/search",
+ "GET /api/projects/*",
+ "GET /api/projects/*/resources",
+ "GET /api/projects/*/subscription",
+ "PUT /api/projects/*/subscription",
+ "DELETE /api/projects/*/subscription",
+
+ // What an issue page needs to render.
+ "GET /api/labels",
+ "GET /api/issue-statuses",
+ "GET /api/issue-workflows",
+ "GET /api/properties",
+ "GET /api/agents",
+ "GET /api/attachments/*",
+ "GET /api/attachments/*/content",
+
+ // The guest's own inbox, pins, view preferences and notification settings.
+ "GET /api/inbox",
+ "GET /api/inbox/*",
+ "GET /api/inbox/*/*",
+ "POST /api/inbox/*",
+ "POST /api/inbox/*/*",
+ "POST /api/inbox/issues/*/read",
+ "DELETE /api/inbox/*",
+ "GET /api/notification-preferences",
+ "PATCH /api/notification-preferences",
+ "PUT /api/notification-preferences",
+ "GET /api/pins",
+ "POST /api/pins",
+ "PUT /api/pins/reorder",
+ "DELETE /api/pins/*/*",
+ "GET /api/issue-view-preferences",
+ "PUT /api/issue-view-preferences",
+
+ // Local search over what the guest can see.
+ "GET /api/search-index/manifest",
+ "GET /api/search-index/snapshot",
+ "POST /api/search-index/changes",
+
+ // User-scoped routes that check membership in the handler.
+ "POST /api/upload-file",
+ "GET /api/attachments/*/download",
+ "GET /api/attachments/*/download-metadata",
+})
+
+// Reads the workspace shell makes on every page (presence, chat badges,
+// runtime health, mention and assignee lists) answer a guest with an empty
+// result instead of 403: the guest has none of these, and an empty answer
+// keeps every component that asks from failing.
+var guestEmptyReads = []struct {
+ route guestRoute
+ body string
+}{
+ {compileGuestRoutes([]string{"GET /api/agent-task-snapshot"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/assignee-frequency"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/chat/sessions"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/chat/pending-tasks"})[0], `{"tasks":[]}`},
+ {compileGuestRoutes([]string{"GET /api/chat/pending-tasks/has-any"})[0], `{"has_pending":false}`},
+ {compileGuestRoutes([]string{"GET /api/runtimes"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/squads"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/squads/involved"})[0], `{"squad_ids":[]}`},
+ {compileGuestRoutes([]string{"GET /api/working-agents"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/issue-wakeup-summaries"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/issue-wakeup-paused"})[0], `[]`},
+ // Saved views and project folders organize the whole workspace; a guest
+ // has neither.
+ {compileGuestRoutes([]string{"GET /api/issue-views"})[0], `[]`},
+ {compileGuestRoutes([]string{"GET /api/project-folders"})[0], `{"folders":[],"filed":[]}`},
+ // The members tab can mount for a moment before settings knows the viewer
+ // is a guest.
+ {compileGuestRoutes([]string{"GET /api/workspaces/*/invitations"})[0], `[]`},
+}
+
+type guestRoute struct {
+ method string
+ segments []string
+}
+
+func compileGuestRoutes(patterns []string) []guestRoute {
+ routes := make([]guestRoute, 0, len(patterns))
+ for _, p := range patterns {
+ method, path, ok := strings.Cut(p, " ")
+ if !ok {
+ panic("guest route without a method: " + p)
+ }
+ routes = append(routes, guestRoute{method: method, segments: splitPath(path)})
+ }
+ return routes
+}
+
+func splitPath(path string) []string {
+ return strings.Split(strings.Trim(path, "/"), "/")
+}
+
+func (route guestRoute) matches(method string, segments []string) bool {
+ if route.method != method || len(route.segments) != len(segments) {
+ return false
+ }
+ for i, s := range route.segments {
+ if s != "*" && s != segments[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// GuestMayRequest reports whether a guest may make this request at all.
+func GuestMayRequest(r *http.Request) bool {
+ segments := splitPath(r.URL.Path)
+ for _, route := range guestRoutes {
+ if route.matches(r.Method, segments) {
+ return true
+ }
+ }
+ return false
+}
+
+// RefuseGuest answers a guest request GuestMayRequest rejected: an empty
+// result for the shell's background reads, 403 for everything else.
+func RefuseGuest(w http.ResponseWriter, r *http.Request) {
+ segments := splitPath(r.URL.Path)
+ for _, read := range guestEmptyReads {
+ if read.route.matches(r.Method, segments) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(read.body))
+ return
+ }
+ }
+ writeError(w, http.StatusForbidden, "insufficient permissions")
+}
diff --git a/server/internal/middleware/workspace.go b/server/internal/middleware/workspace.go
index 4fb58c33c8..9b5b2bf684 100644
--- a/server/internal/middleware/workspace.go
+++ b/server/internal/middleware/workspace.go
@@ -245,6 +245,10 @@ func buildMiddleware(queries *db.Queries, resolve workspaceResolver, roles []str
writeError(w, http.StatusNotFound, "workspace not found")
return
}
+ if member.Role == "guest" && !GuestMayRequest(r) {
+ RefuseGuest(w, r)
+ return
+ }
if len(roles) > 0 {
allowed := false
diff --git a/server/internal/projectaccess/projectaccess.go b/server/internal/projectaccess/projectaccess.go
index 3a9eb8765b..a6ec2dddce 100644
--- a/server/internal/projectaccess/projectaccess.go
+++ b/server/internal/projectaccess/projectaccess.go
@@ -8,6 +8,11 @@
// members (MUL-9284). Every other project is visible to every workspace
// member. An issue's visibility is its project's.
//
+// A guest (MUL-9420) sees only the projects it is a member of, whatever their
+// visibility, and nothing outside a project. Its hidden set therefore holds
+// every other project plus NoProject, which stands in for "no project" so the
+// same SQL predicates (COALESCE(project_id, NoProject)) hide project-less rows.
+//
// A viewer is a set of principals (human user ids). A member request has one
// principal: the member. An agent run has two: the human who triggered it and
// the agent's owner, and sees a private project only when both can. A viewer
@@ -27,8 +32,19 @@ import (
const (
VisibilityWorkspace = "workspace"
VisibilityPrivate = "private"
+
+ RoleGuest = "guest"
)
+// NoProject is the hidden-set entry for objects outside any project. It is the
+// nil UUID, which no project id can be.
+var NoProject = pgtype.UUID{Valid: true}
+
+// IsGuestRole reports whether a workspace role is the project-scoped guest.
+func IsGuestRole(role string) bool {
+ return role == RoleGuest
+}
+
// ValidVisibility reports whether v is a storable project visibility.
func ValidVisibility(v string) bool {
return v == VisibilityWorkspace || v == VisibilityPrivate
@@ -44,6 +60,7 @@ func IsManagerRole(role string) bool {
type Querier interface {
GetMemberByUserAndWorkspace(ctx context.Context, arg db.GetMemberByUserAndWorkspaceParams) (db.Member, error)
ListHiddenProjectIDsForUser(ctx context.Context, arg db.ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error)
+ ListHiddenProjectIDsForGuest(ctx context.Context, arg db.ListHiddenProjectIDsForGuestParams) ([]pgtype.UUID, error)
ListPrivateProjectIDs(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error)
}
@@ -73,11 +90,15 @@ func (h *Hidden) add(ids []pgtype.UUID) {
func (h Hidden) Empty() bool { return len(h.ids) == 0 }
// CanSeeProject reports whether an object in projectID is visible. Objects
-// outside any project (invalid projectID) are always visible.
+// outside any project (invalid projectID) are visible unless the set hides
+// NoProject.
func (h Hidden) CanSeeProject(projectID pgtype.UUID) bool {
- if !projectID.Valid || len(h.set) == 0 {
+ if len(h.set) == 0 {
return true
}
+ if !projectID.Valid {
+ projectID = NoProject
+ }
_, hidden := h.set[projectID.Bytes]
return !hidden
}
@@ -100,12 +121,25 @@ func (h Hidden) IDs() []pgtype.UUID {
}
// ForMember computes the hidden set for one current workspace member: every
-// private project they are not a member of.
-func ForMember(ctx context.Context, q Querier, workspaceID, userID pgtype.UUID) (Hidden, error) {
+// private project they are not a member of, or for a guest every project they
+// are not a member of and everything outside a project.
+func ForMember(ctx context.Context, q Querier, member db.Member) (Hidden, error) {
h := newHidden()
+ if IsGuestRole(member.Role) {
+ ids, err := q.ListHiddenProjectIDsForGuest(ctx, db.ListHiddenProjectIDsForGuestParams{
+ WorkspaceID: member.WorkspaceID,
+ UserID: member.UserID,
+ })
+ if err != nil {
+ return Hidden{}, err
+ }
+ h.add([]pgtype.UUID{NoProject})
+ h.add(ids)
+ return h, nil
+ }
ids, err := q.ListHiddenProjectIDsForUser(ctx, db.ListHiddenProjectIDsForUserParams{
- WorkspaceID: workspaceID,
- UserID: userID,
+ WorkspaceID: member.WorkspaceID,
+ UserID: member.UserID,
})
if err != nil {
return Hidden{}, err
@@ -125,9 +159,6 @@ func ForPrincipals(ctx context.Context, q Querier, workspaceID pgtype.UUID, prin
if err != nil {
return Hidden{}, err
}
- if len(private) == 0 {
- return h, nil
- }
all := newHidden()
all.add(private)
seen := map[[16]byte]struct{}{}
@@ -146,7 +177,7 @@ func ForPrincipals(ctx context.Context, q Querier, workspaceID pgtype.UUID, prin
return all, nil
}
for _, p := range valid {
- _, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
UserID: p,
WorkspaceID: workspaceID,
})
@@ -156,7 +187,11 @@ func ForPrincipals(ctx context.Context, q Querier, workspaceID pgtype.UUID, prin
if err != nil {
return Hidden{}, err
}
- one, err := ForMember(ctx, q, workspaceID, p)
+ // Without private projects only a guest has anything hidden.
+ if len(private) == 0 && !IsGuestRole(member.Role) {
+ continue
+ }
+ one, err := ForMember(ctx, q, member)
if err != nil {
return Hidden{}, err
}
diff --git a/server/internal/projectaccess/projectaccess_test.go b/server/internal/projectaccess/projectaccess_test.go
index 5d0e898d5c..7fa255e157 100644
--- a/server/internal/projectaccess/projectaccess_test.go
+++ b/server/internal/projectaccess/projectaccess_test.go
@@ -19,13 +19,15 @@ func uid(b byte) pgtype.UUID {
// fakeQuerier: private projects p1 and p2. User 1 is a member of both, user 2
// of p1 only, user 3 of neither. User 5 is a workspace admin and user 6 the
-// workspace owner, members of neither. User 4 is not in the workspace.
+// workspace owner, members of neither. User 4 is not in the workspace. User 7
+// is a guest of p1, and p3 is a workspace-visible project.
type fakeQuerier struct{}
var (
- p1, p2 = uid(101), uid(102)
+ p1, p2, p3 = uid(101), uid(102), uid(103)
bothMember, p1Member, nonMember = uid(1), uid(2), uid(3)
notInWork, outsideAdmin, outsideOwner = uid(4), uid(5), uid(6)
+ p1Guest = uid(7)
)
func (fakeQuerier) GetMemberByUserAndWorkspace(_ context.Context, arg db.GetMemberByUserAndWorkspaceParams) (db.Member, error) {
@@ -36,6 +38,8 @@ func (fakeQuerier) GetMemberByUserAndWorkspace(_ context.Context, arg db.GetMemb
return db.Member{UserID: arg.UserID, Role: "admin"}, nil
case bothMember, p1Member, nonMember:
return db.Member{UserID: arg.UserID, Role: "member"}, nil
+ case p1Guest:
+ return db.Member{UserID: arg.UserID, Role: RoleGuest}, nil
}
return db.Member{}, pgx.ErrNoRows
}
@@ -50,6 +54,13 @@ func (fakeQuerier) ListHiddenProjectIDsForUser(_ context.Context, arg db.ListHid
return []pgtype.UUID{p1, p2}, nil
}
+func (fakeQuerier) ListHiddenProjectIDsForGuest(_ context.Context, arg db.ListHiddenProjectIDsForGuestParams) ([]pgtype.UUID, error) {
+ if arg.UserID == p1Guest {
+ return []pgtype.UUID{p2, p3}, nil
+ }
+ return []pgtype.UUID{p1, p2, p3}, nil
+}
+
func (fakeQuerier) ListPrivateProjectIDs(context.Context, pgtype.UUID) ([]pgtype.UUID, error) {
return []pgtype.UUID{p1, p2}, nil
}
@@ -72,6 +83,7 @@ func TestForPrincipals(t *testing.T) {
{"principal outside the workspace sees nothing private", []pgtype.UUID{bothMember, notInWork}, false, false},
{"no principal sees nothing private", nil, false, false},
{"invalid principals are ignored", []pgtype.UUID{{}, p1Member}, true, false},
+ {"guest sees its project only", []pgtype.UUID{p1Guest}, true, false},
} {
hidden, err := ForPrincipals(context.Background(), fakeQuerier{}, ws, tc.principals...)
if err != nil {
@@ -83,6 +95,9 @@ func TestForPrincipals(t *testing.T) {
if got := hidden.CanSeeProject(p2); got != tc.seeP2 {
t.Errorf("%s: p2 visible = %v, want %v", tc.name, got, tc.seeP2)
}
+ if tc.principals != nil && tc.principals[0] == p1Guest {
+ continue
+ }
if !hidden.CanSeeProject(pgtype.UUID{}) {
t.Errorf("%s: an object outside any project must stay visible", tc.name)
}
@@ -90,7 +105,7 @@ func TestForPrincipals(t *testing.T) {
}
func TestHiddenParamIsNilWhenNothingHidden(t *testing.T) {
- hidden, err := ForMember(context.Background(), fakeQuerier{}, uid(200), bothMember)
+ hidden, err := ForMember(context.Background(), fakeQuerier{}, db.Member{WorkspaceID: uid(200), UserID: bothMember, Role: "member"})
if err != nil {
t.Fatal(err)
}
@@ -113,3 +128,42 @@ func TestRunPrincipalsFallsBackToAccountableUser(t *testing.T) {
t.Fatalf("originator must win over accountable: %v", got)
}
}
+
+func TestGuestSeesOnlyItsProjects(t *testing.T) {
+ hidden, err := ForMember(context.Background(), fakeQuerier{}, db.Member{WorkspaceID: uid(200), UserID: p1Guest, Role: RoleGuest})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !hidden.CanSeeProject(p1) {
+ t.Error("a guest must see its project")
+ }
+ if hidden.CanSeeProject(p2) || hidden.CanSeeProject(p3) {
+ t.Error("a guest must not see other projects, private or not")
+ }
+ if hidden.CanSeeProject(pgtype.UUID{}) {
+ t.Error("a guest must not see objects outside any project")
+ }
+ found := false
+ for _, id := range hidden.Param() {
+ found = found || id == NoProject
+ }
+ if !found {
+ t.Error("the SQL parameter must carry NoProject so project-less rows are filtered")
+ }
+}
+
+func TestGuestBoundsARunEvenWithoutPrivateProjects(t *testing.T) {
+ hidden, err := ForPrincipals(context.Background(), noPrivateQuerier{}, uid(200), bothMember, p1Guest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if hidden.CanSeeProject(p3) || hidden.CanSeeProject(pgtype.UUID{}) {
+ t.Error("a guest principal must narrow the viewer in a workspace without private projects")
+ }
+}
+
+type noPrivateQuerier struct{ fakeQuerier }
+
+func (noPrivateQuerier) ListPrivateProjectIDs(context.Context, pgtype.UUID) ([]pgtype.UUID, error) {
+ return nil, nil
+}
diff --git a/server/internal/service/agent_invocation.go b/server/internal/service/agent_invocation.go
index 63808cd204..e69548b387 100644
--- a/server/internal/service/agent_invocation.go
+++ b/server/internal/service/agent_invocation.go
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -38,28 +39,32 @@ func memberMayInvokeAgent(ctx context.Context, queries *db.Queries, agent db.Age
if userID == "" {
return false, nil
}
- if util.UUIDToString(agent.OwnerID) == userID {
- return true, nil
- }
- if agent.PermissionMode != "public_to" {
- return false, nil
- }
- targets, err := queries.ListAgentInvocationTargets(ctx, agent.ID)
- if err != nil {
- return false, fmt.Errorf("list agent invocation targets: %w", err)
- }
isWorkspaceMember := false
- switch _, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ switch member, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
UserID: memberUserID,
WorkspaceID: workspaceID,
}); {
case err == nil:
+ // Guests never run agents (MUL-9420).
+ if projectaccess.IsGuestRole(member.Role) {
+ return false, nil
+ }
isWorkspaceMember = true
case errors.Is(err, pgx.ErrNoRows):
// Not a member. A fact, not a failure.
default:
return false, fmt.Errorf("load workspace member: %w", err)
}
+ if util.UUIDToString(agent.OwnerID) == userID {
+ return true, nil
+ }
+ if agent.PermissionMode != "public_to" {
+ return false, nil
+ }
+ targets, err := queries.ListAgentInvocationTargets(ctx, agent.ID)
+ if err != nil {
+ return false, fmt.Errorf("list agent invocation targets: %w", err)
+ }
for _, t := range targets {
switch t.TargetType {
case "workspace":
diff --git a/server/internal/service/chat_wakeup_test.go b/server/internal/service/chat_wakeup_test.go
index 709c7b791a..0a9ea0f0f0 100644
--- a/server/internal/service/chat_wakeup_test.go
+++ b/server/internal/service/chat_wakeup_test.go
@@ -385,7 +385,7 @@ func TestChatWakeupHonorsPrivateProjects(t *testing.T) {
secret := f.fx.Project(t, "Secret", testutil.Cols{"visibility": "private"})
hidden := f.fx.Issue(t, "Secret issue", testutil.Cols{"project_id": secret})
- if access, err := projectaccess.ForMember(ctx, f.q, util.MustParseUUID(f.fx.WorkspaceID), util.MustParseUUID(member)); err != nil || access.CanSeeProject(util.MustParseUUID(secret)) {
+ if access, err := projectaccess.ForPrincipals(ctx, f.q, util.MustParseUUID(f.fx.WorkspaceID), util.MustParseUUID(member)); err != nil || access.CanSeeProject(util.MustParseUUID(secret)) {
t.Fatalf("fixture: member can see the private project (err=%v)", err)
}
cond, _ := json.Marshal(map[string]any{"type": "issue_reply", "issue_id": hidden})
diff --git a/server/migrations/699_member_guest_role.down.sql b/server/migrations/699_member_guest_role.down.sql
new file mode 100644
index 0000000000..f634a9a200
--- /dev/null
+++ b/server/migrations/699_member_guest_role.down.sql
@@ -0,0 +1,13 @@
+-- Guests and guest invitations must be removed (or converted to members)
+-- before rolling back; the restored constraints reject them on the next write.
+ALTER TABLE workspace_invitation DROP COLUMN IF EXISTS project_ids;
+
+ALTER TABLE workspace_invitation
+ DROP CONSTRAINT IF EXISTS workspace_invitation_role_check,
+ ADD CONSTRAINT workspace_invitation_role_check
+ CHECK (role IN ('admin', 'member')) NOT VALID;
+
+ALTER TABLE member
+ DROP CONSTRAINT IF EXISTS member_role_check,
+ ADD CONSTRAINT member_role_check
+ CHECK (role IN ('owner', 'admin', 'member')) NOT VALID;
diff --git a/server/migrations/699_member_guest_role.up.sql b/server/migrations/699_member_guest_role.up.sql
new file mode 100644
index 0000000000..b3c130e84f
--- /dev/null
+++ b/server/migrations/699_member_guest_role.up.sql
@@ -0,0 +1,19 @@
+-- MUL-9420: guests. A guest is a workspace member row with role 'guest' that
+-- sees only the projects it is a project_member of. An invitation records the
+-- projects a guest invitee will join on acceptance.
+--
+-- Widening a whitelist cannot fail on existing rows, so the constraints are
+-- replaced NOT VALID (no scan), the same as 610. The project_ids default is a
+-- constant, which keeps the ADD COLUMN catalog-only.
+ALTER TABLE member
+ DROP CONSTRAINT IF EXISTS member_role_check,
+ ADD CONSTRAINT member_role_check
+ CHECK (role IN ('owner', 'admin', 'member', 'guest')) NOT VALID;
+
+ALTER TABLE workspace_invitation
+ DROP CONSTRAINT IF EXISTS workspace_invitation_role_check,
+ ADD CONSTRAINT workspace_invitation_role_check
+ CHECK (role IN ('admin', 'member', 'guest')) NOT VALID;
+
+ALTER TABLE workspace_invitation
+ ADD COLUMN IF NOT EXISTS project_ids UUID[] NOT NULL DEFAULT '{}';
diff --git a/server/migrations/700_member_search_access.down.sql b/server/migrations/700_member_search_access.down.sql
new file mode 100644
index 0000000000..9ff01243ec
--- /dev/null
+++ b/server/migrations/700_member_search_access.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS member_search_access;
diff --git a/server/migrations/700_member_search_access.up.sql b/server/migrations/700_member_search_access.up.sql
new file mode 100644
index 0000000000..d5aab6573b
--- /dev/null
+++ b/server/migrations/700_member_search_access.up.sql
@@ -0,0 +1,17 @@
+-- MUL-9420: when what a member can see changes without the content changing
+-- (a member becomes a guest, a guest gains or loses a project, a guest
+-- becomes a member), local search sync has no change row to deliver. The
+-- transaction that changes the access records its xid here; a search index
+-- cursor whose snapshot does not include that xid was built under the old
+-- access and must be rebuilt.
+--
+-- One row per (workspace, user), overwritten by each change. The primary key
+-- attaches after a concurrent build (701, 702). No foreign keys (repo rule):
+-- a row outliving its member is inert, because a later snapshot always
+-- includes its xid.
+CREATE TABLE IF NOT EXISTS member_search_access (
+ workspace_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ changed_xid xid8 NOT NULL,
+ changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/701_member_search_access_pkey_index.down.sql b/server/migrations/701_member_search_access_pkey_index.down.sql
new file mode 100644
index 0000000000..bce363e05c
--- /dev/null
+++ b/server/migrations/701_member_search_access_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS member_search_access_pkey_idx;
diff --git a/server/migrations/701_member_search_access_pkey_index.up.sql b/server/migrations/701_member_search_access_pkey_index.up.sql
new file mode 100644
index 0000000000..ad5e668e2d
--- /dev/null
+++ b/server/migrations/701_member_search_access_pkey_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS member_search_access_pkey_idx ON member_search_access (workspace_id, user_id);
diff --git a/server/migrations/702_member_search_access_pkey.down.sql b/server/migrations/702_member_search_access_pkey.down.sql
new file mode 100644
index 0000000000..e473b6a240
--- /dev/null
+++ b/server/migrations/702_member_search_access_pkey.down.sql
@@ -0,0 +1 @@
+ALTER TABLE member_search_access DROP CONSTRAINT IF EXISTS member_search_access_pkey;
diff --git a/server/migrations/702_member_search_access_pkey.up.sql b/server/migrations/702_member_search_access_pkey.up.sql
new file mode 100644
index 0000000000..b945da610d
--- /dev/null
+++ b/server/migrations/702_member_search_access_pkey.up.sql
@@ -0,0 +1 @@
+ALTER TABLE member_search_access ADD CONSTRAINT member_search_access_pkey PRIMARY KEY USING INDEX member_search_access_pkey_idx;
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index d850e0d0ad..3e6b6cb36f 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -53,6 +53,47 @@ func (q *Queries) BindChatAttachmentsToMessage(ctx context.Context, arg BindChat
return items, nil
}
+const bindUploaderDraftAttachmentsToIssue = `-- name: BindUploaderDraftAttachmentsToIssue :execrows
+UPDATE attachment
+SET issue_id = $1
+WHERE workspace_id = $2
+ AND id = ANY($3::uuid[])
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_session_id IS NULL
+ AND chat_message_id IS NULL
+ AND task_id IS NULL
+ AND source_context_id IS NULL
+ AND uploader_type = $4
+ AND uploader_id = $5
+`
+
+type BindUploaderDraftAttachmentsToIssueParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID pgtype.UUID `json:"uploader_id"`
+}
+
+// A comment edit's own drafts: attachments the editor uploaded that are not
+// bound to anything yet (a guest's uploads stay unbound until a comment takes
+// them, MUL-9420) join the comment's issue, so ReplaceCommentAttachments can
+// link them in the same transaction.
+func (q *Queries) BindUploaderDraftAttachmentsToIssue(ctx context.Context, arg BindUploaderDraftAttachmentsToIssueParams) (int64, error) {
+ result, err := q.db.Exec(ctx, bindUploaderDraftAttachmentsToIssue,
+ arg.IssueID,
+ arg.WorkspaceID,
+ arg.AttachmentIds,
+ arg.UploaderType,
+ arg.UploaderID,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const countUnboundChatAttachmentsForTask = `-- name: CountUnboundChatAttachmentsForTask :one
SELECT COUNT(*) FROM attachment
WHERE workspace_id = $1
@@ -572,24 +613,33 @@ WHERE workspace_id = $3
AND chat_session_id IS NULL
AND chat_message_id IS NULL
AND task_id IS NULL
+ AND uploader_type = $4
+ AND uploader_id = $5
))
AND comment_id IS NULL
AND source_context_id IS NULL
- AND id = ANY($4::uuid[])
+ AND id = ANY($6::uuid[])
`
type LinkAttachmentsToCommentParams struct {
CommentID pgtype.UUID `json:"comment_id"`
IssueID pgtype.UUID `json:"issue_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID pgtype.UUID `json:"uploader_id"`
AttachmentIds []pgtype.UUID `json:"attachment_ids"`
}
+// An unbound upload is a draft and joins only its own uploader's comment
+// (MUL-9420): a guest's file taken off its comment must not be adoptable by
+// anyone else who learns its id.
func (q *Queries) LinkAttachmentsToComment(ctx context.Context, arg LinkAttachmentsToCommentParams) error {
_, err := q.db.Exec(ctx, linkAttachmentsToComment,
arg.CommentID,
arg.IssueID,
arg.WorkspaceID,
+ arg.UploaderType,
+ arg.UploaderID,
arg.AttachmentIds,
)
return err
@@ -1037,6 +1087,41 @@ func (q *Queries) ListAttachmentsBySourceContext(ctx context.Context, arg ListAt
return items, nil
}
+const listCommentAttachmentIDsAmong = `-- name: ListCommentAttachmentIDsAmong :many
+SELECT id FROM attachment
+WHERE comment_id = $1
+ AND workspace_id = $2
+ AND id = ANY($3::uuid[])
+`
+
+type ListCommentAttachmentIDsAmongParams struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+}
+
+// Which of attachment_ids are attached to the comment: an edit checks that
+// it got every file it asked for before committing.
+func (q *Queries) ListCommentAttachmentIDsAmong(ctx context.Context, arg ListCommentAttachmentIDsAmongParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listCommentAttachmentIDsAmong, arg.CommentID, arg.WorkspaceID, arg.AttachmentIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listSourceContextAttachmentURLsByWorkspace = `-- name: ListSourceContextAttachmentURLsByWorkspace :many
SELECT url FROM attachment
WHERE workspace_id = $1
@@ -1308,21 +1393,31 @@ WHERE workspace_id = $1
AND chat_message_id IS NULL
AND task_id IS NULL
AND source_context_id IS NULL
- AND id = ANY($2::uuid[])
+ AND uploader_type = $2
+ AND uploader_id = $3
+ AND id = ANY($4::uuid[])
ORDER BY id
FOR UPDATE
`
type LockUnboundAttachmentsForCommentLinkParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UploaderType string `json:"uploader_type"`
+ UploaderID pgtype.UUID `json:"uploader_id"`
AttachmentIds []pgtype.UUID `json:"attachment_ids"`
}
// Like issue updates, comment creation locks ownerless uploads before the
// issue row. Once it takes the issue, it locks existing issue children below.
// This keeps both upload adoption and owner-first deletion in the same order.
+// Only the comment author's own uploads qualify (see LinkAttachmentsToComment).
func (q *Queries) LockUnboundAttachmentsForCommentLink(ctx context.Context, arg LockUnboundAttachmentsForCommentLinkParams) ([]pgtype.UUID, error) {
- rows, err := q.db.Query(ctx, lockUnboundAttachmentsForCommentLink, arg.WorkspaceID, arg.AttachmentIds)
+ rows, err := q.db.Query(ctx, lockUnboundAttachmentsForCommentLink,
+ arg.WorkspaceID,
+ arg.UploaderType,
+ arg.UploaderID,
+ arg.AttachmentIds,
+ )
if err != nil {
return nil, err
}
@@ -1346,6 +1441,16 @@ UPDATE attachment
SET comment_id = CASE
WHEN id = ANY($3::uuid[]) THEN $1
ELSE NULL
+END,
+issue_id = CASE
+ WHEN id = ANY($3::uuid[]) THEN issue_id
+ WHEN uploader_type = 'member' AND EXISTS (
+ SELECT 1 FROM member m
+ WHERE m.workspace_id = attachment.workspace_id
+ AND m.user_id = attachment.uploader_id
+ AND m.role = 'guest'
+ ) THEN NULL
+ ELSE issue_id
END
WHERE issue_id = $2
AND source_context_id IS NULL
@@ -1361,6 +1466,9 @@ type ReplaceCommentAttachmentsParams struct {
AttachmentIds []pgtype.UUID `json:"attachment_ids"`
}
+// A file removed from the comment stays an issue attachment, except a guest's
+// (MUL-9420): a guest attaches files only through its comments, so its file
+// goes back to being its unbound draft rather than staying on the issue.
func (q *Queries) ReplaceCommentAttachments(ctx context.Context, arg ReplaceCommentAttachmentsParams) (int64, error) {
result, err := q.db.Exec(ctx, replaceCommentAttachments, arg.CommentID, arg.IssueID, arg.AttachmentIds)
if err != nil {
diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.go
index e3bf712328..764de32552 100644
--- a/server/pkg/db/generated/github.sql.go
+++ b/server/pkg/db/generated/github.sql.go
@@ -589,7 +589,7 @@ JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id
JOIN issue i ON i.id = ipr.issue_id
WHERE pr.workspace_id = $1
AND i.workspace_id = $1
- AND ($2::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($2::uuid[])))
+ AND ($2::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($2::uuid[])))
UNION ALL
SELECT
ipr.issue_id,
@@ -600,7 +600,7 @@ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id
JOIN issue i ON i.id = ipr.issue_id
WHERE pr.workspace_id = $1
AND i.workspace_id = $1
- AND ($2::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($2::uuid[])))
+ AND ($2::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($2::uuid[])))
ORDER BY pr_created_at DESC
`
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index ad7ec48a52..bc66649cbf 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -207,8 +207,8 @@ WITH boundary AS MATERIALIZED (
AND b.recipient_id = $3
AND b.archived = false
AND (b.snoozed_until IS NULL OR b.snoozed_until <= now())
- AND ($4::uuid[] IS NULL OR b_iss.project_id IS NULL
- OR NOT (b_iss.project_id = ANY($4::uuid[])))
+ AND ($4::uuid[] IS NULL
+ OR NOT (COALESCE(b_iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])))
ORDER BY GREATEST(b.created_at, b.returned_at) DESC, b.id DESC
OFFSET $5::int - 1
LIMIT 1
@@ -220,8 +220,8 @@ WITH boundary AS MATERIALIZED (
AND o.recipient_id = $3
AND o.archived = false
AND (o.snoozed_until IS NULL OR o.snoozed_until <= now())
- AND ($4::uuid[] IS NULL OR o_iss.project_id IS NULL
- OR NOT (o_iss.project_id = ANY($4::uuid[])))
+ AND ($4::uuid[] IS NULL
+ OR NOT (COALESCE(o_iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])))
AND (GREATEST(o.created_at, o.returned_at), o.id) < (boundary.shown_at, boundary.id)
-- An issue back from a snooze whose newest row does not carry the
-- return yet (written by an older server, or not normalized) ranks too
@@ -331,7 +331,7 @@ WHERE i.workspace_id = $1
AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY($4::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])
))
`
@@ -628,8 +628,8 @@ SELECT count(*) > 0 FROM (
WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3
AND i.archived = false
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
- AND ($4::uuid[] IS NULL OR iss.project_id IS NULL
- OR NOT (iss.project_id = ANY($4::uuid[])))
+ AND ($4::uuid[] IS NULL
+ OR NOT (COALESCE(iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])))
ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
OFFSET $5::int
LIMIT 1
@@ -719,7 +719,7 @@ WITH eligible_archived AS MATERIALIZED (
AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY($4::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])
))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1
@@ -902,7 +902,7 @@ WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND
-- whose time has passed is listed again and keeps snoozed_until, which is
-- how the client tells an issue that came back on its own.
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
- AND ($4::uuid[] IS NULL OR iss.project_id IS NULL OR NOT (iss.project_id = ANY($4::uuid[])))
+ AND ($4::uuid[] IS NULL OR NOT (COALESCE(iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($4::uuid[])))
ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
LIMIT $5
`
@@ -1028,7 +1028,7 @@ FROM (
AND ($3::uuid[] IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY($3::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])
))
GROUP BY i.issue_id
) g
diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.go
index d8e3e1509e..1faa9499ca 100644
--- a/server/pkg/db/generated/inbox_archive.sql.go
+++ b/server/pkg/db/generated/inbox_archive.sql.go
@@ -34,7 +34,7 @@ WITH base AS MATERIALIZED (
AND ($3::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY($3::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])
))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM inbox_item active
@@ -229,7 +229,7 @@ WITH base AS MATERIALIZED (
AND ($3::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY($3::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])
))
AND ($4::uuid IS NULL OR i.issue_id = $4::uuid
OR (i.issue_id IS NULL AND i.id = $4::uuid))
diff --git a/server/pkg/db/generated/invitation.sql.go b/server/pkg/db/generated/invitation.sql.go
index a2e45a0c6d..92c472eb82 100644
--- a/server/pkg/db/generated/invitation.sql.go
+++ b/server/pkg/db/generated/invitation.sql.go
@@ -15,7 +15,7 @@ const acceptInvitation = `-- name: AcceptInvitation :one
UPDATE workspace_invitation
SET status = 'accepted', updated_at = now()
WHERE id = $1 AND status = 'pending'
-RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at
+RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at, project_ids
`
func (q *Queries) AcceptInvitation(ctx context.Context, id pgtype.UUID) (WorkspaceInvitation, error) {
@@ -32,14 +32,15 @@ func (q *Queries) AcceptInvitation(ctx context.Context, id pgtype.UUID) (Workspa
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
)
return i, err
}
const createInvitation = `-- name: CreateInvitation :one
-INSERT INTO workspace_invitation (id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, expires_at)
-VALUES ($1, $2, $3, $4, $5, $6, $7)
-RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at
+INSERT INTO workspace_invitation (id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, expires_at, project_ids)
+VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8::uuid[], '{}'))
+RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at, project_ids
`
type CreateInvitationParams struct {
@@ -50,6 +51,7 @@ type CreateInvitationParams struct {
InviteeUserID pgtype.UUID `json:"invitee_user_id"`
Role string `json:"role"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
}
func (q *Queries) CreateInvitation(ctx context.Context, arg CreateInvitationParams) (WorkspaceInvitation, error) {
@@ -61,6 +63,7 @@ func (q *Queries) CreateInvitation(ctx context.Context, arg CreateInvitationPara
arg.InviteeUserID,
arg.Role,
arg.ExpiresAt,
+ arg.ProjectIds,
)
var i WorkspaceInvitation
err := row.Scan(
@@ -74,6 +77,7 @@ func (q *Queries) CreateInvitation(ctx context.Context, arg CreateInvitationPara
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
)
return i, err
}
@@ -82,7 +86,7 @@ const declineInvitation = `-- name: DeclineInvitation :one
UPDATE workspace_invitation
SET status = 'declined', updated_at = now()
WHERE id = $1 AND status = 'pending'
-RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at
+RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at, project_ids
`
func (q *Queries) DeclineInvitation(ctx context.Context, id pgtype.UUID) (WorkspaceInvitation, error) {
@@ -99,6 +103,7 @@ func (q *Queries) DeclineInvitation(ctx context.Context, id pgtype.UUID) (Worksp
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
)
return i, err
}
@@ -110,7 +115,7 @@ WHERE workspace_id = $1
AND invitee_email = $2
AND status = 'pending'
AND expires_at <= now()
-RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at
+RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at, project_ids
`
type ExpireStalePendingInvitationsParams struct {
@@ -142,6 +147,7 @@ func (q *Queries) ExpireStalePendingInvitations(ctx context.Context, arg ExpireS
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
); err != nil {
return nil, err
}
@@ -154,7 +160,7 @@ func (q *Queries) ExpireStalePendingInvitations(ctx context.Context, arg ExpireS
}
const getInvitation = `-- name: GetInvitation :one
-SELECT id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at FROM workspace_invitation
+SELECT id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at, project_ids FROM workspace_invitation
WHERE id = $1
`
@@ -172,12 +178,13 @@ func (q *Queries) GetInvitation(ctx context.Context, id pgtype.UUID) (WorkspaceI
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
)
return i, err
}
const getPendingInvitationByEmail = `-- name: GetPendingInvitationByEmail :one
-SELECT id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at FROM workspace_invitation
+SELECT id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at, project_ids FROM workspace_invitation
WHERE workspace_id = $1 AND invitee_email = $2 AND status = 'pending' AND expires_at > now()
`
@@ -200,6 +207,7 @@ func (q *Queries) GetPendingInvitationByEmail(ctx context.Context, arg GetPendin
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
)
return i, err
}
@@ -222,7 +230,7 @@ func (q *Queries) HasPendingInvitationForEmail(ctx context.Context, inviteeEmail
}
const listPendingInvitationsByWorkspace = `-- name: ListPendingInvitationsByWorkspace :many
-SELECT wi.id, wi.workspace_id, wi.inviter_id, wi.invitee_email, wi.invitee_user_id, wi.role, wi.status, wi.created_at, wi.updated_at, wi.expires_at,
+SELECT wi.id, wi.workspace_id, wi.inviter_id, wi.invitee_email, wi.invitee_user_id, wi.role, wi.status, wi.created_at, wi.updated_at, wi.expires_at, wi.project_ids,
u.name AS inviter_name,
u.email AS inviter_email
FROM workspace_invitation wi
@@ -242,6 +250,7 @@ type ListPendingInvitationsByWorkspaceRow struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
InviterName string `json:"inviter_name"`
InviterEmail string `json:"inviter_email"`
}
@@ -266,6 +275,7 @@ func (q *Queries) ListPendingInvitationsByWorkspace(ctx context.Context, workspa
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
&i.InviterName,
&i.InviterEmail,
); err != nil {
@@ -280,7 +290,7 @@ func (q *Queries) ListPendingInvitationsByWorkspace(ctx context.Context, workspa
}
const listPendingInvitationsForUser = `-- name: ListPendingInvitationsForUser :many
-SELECT wi.id, wi.workspace_id, wi.inviter_id, wi.invitee_email, wi.invitee_user_id, wi.role, wi.status, wi.created_at, wi.updated_at, wi.expires_at,
+SELECT wi.id, wi.workspace_id, wi.inviter_id, wi.invitee_email, wi.invitee_user_id, wi.role, wi.status, wi.created_at, wi.updated_at, wi.expires_at, wi.project_ids,
w.name AS workspace_name,
u.name AS inviter_name,
u.email AS inviter_email
@@ -309,6 +319,7 @@ type ListPendingInvitationsForUserRow struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
WorkspaceName string `json:"workspace_name"`
InviterName string `json:"inviter_name"`
InviterEmail string `json:"inviter_email"`
@@ -334,6 +345,7 @@ func (q *Queries) ListPendingInvitationsForUser(ctx context.Context, arg ListPen
&i.CreatedAt,
&i.UpdatedAt,
&i.ExpiresAt,
+ &i.ProjectIds,
&i.WorkspaceName,
&i.InviterName,
&i.InviterEmail,
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 93d162322d..eade2901db 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -19,7 +19,7 @@ FROM issue
WHERE workspace_id = $1
AND parent_issue_id IS NOT NULL
-- MUL-8472: private projects the caller cannot see.
- AND ($3::uuid[] IS NULL OR project_id IS NULL OR NOT (project_id = ANY($3::uuid[])))
+ AND ($3::uuid[] IS NULL OR NOT (COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])))
GROUP BY parent_issue_id
`
@@ -185,7 +185,7 @@ WHERE i.workspace_id = $1
AND ($7::uuid IS NULL OR (i.creator_type = 'member' AND i.creator_id = $7) OR i.requester_user_id = $7)
AND ($8::uuid IS NULL OR i.project_id = $8)
-- MUL-8472: private projects the caller cannot see.
- AND ($9::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($9::uuid[])))
+ AND ($9::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($9::uuid[])))
AND ($10::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))
AND ($11::jsonb IS NULL OR i.metadata @> $11::jsonb)
AND (
@@ -1412,7 +1412,7 @@ WHERE i.workspace_id = $1
AND ($9::uuid IS NULL OR (i.creator_type = 'member' AND i.creator_id = $9) OR i.requester_user_id = $9)
AND ($10::uuid IS NULL OR i.project_id = $10)
-- MUL-8472: private projects the caller cannot see.
- AND ($11::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($11::uuid[])))
+ AND ($11::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($11::uuid[])))
AND ($12::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))
AND ($13::jsonb IS NULL OR i.metadata @> $13::jsonb)
AND (
@@ -1587,7 +1587,7 @@ WHERE i.workspace_id = $1
AND ($7::uuid IS NULL OR (i.creator_type = 'member' AND i.creator_id = $7) OR i.requester_user_id = $7)
AND ($8::uuid IS NULL OR i.project_id = $8)
-- MUL-8472: private projects the caller cannot see.
- AND ($9::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($9::uuid[])))
+ AND ($9::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($9::uuid[])))
AND ($10::jsonb IS NULL OR i.metadata @> $10::jsonb)
-- properties_filter is a jsonb array of groups, each group an array of
-- patterns (built by parsePropertiesFilterParam): the issue must match at
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
index 41ae830dc1..56b552674c 100644
--- a/server/pkg/db/generated/issue_label.sql.go
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -397,7 +397,7 @@ SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.reso
AND ($1::uuid[] IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = x.issue_id
- AND hidden_issue.project_id = ANY($1::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($1::uuid[])
)))
WHEN 'agent' THEN (SELECT COUNT(*) FROM agent_to_label x WHERE x.label_id = l.id)
WHEN 'skill' THEN (SELECT COUNT(*) FROM skill_to_label x WHERE x.label_id = l.id)
diff --git a/server/pkg/db/generated/issue_unread.sql.go b/server/pkg/db/generated/issue_unread.sql.go
index 4e441fde9f..dbdcdd1276 100644
--- a/server/pkg/db/generated/issue_unread.sql.go
+++ b/server/pkg/db/generated/issue_unread.sql.go
@@ -29,7 +29,7 @@ WHERE u.workspace_id = $1
AND ($3::uuid[] IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = u.issue_id
- AND hidden_issue.project_id = ANY($3::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])
))
AND (
$4::timestamptz IS NULL
diff --git a/server/pkg/db/generated/member.sql.go b/server/pkg/db/generated/member.sql.go
index b1551a6d64..97624636e2 100644
--- a/server/pkg/db/generated/member.sql.go
+++ b/server/pkg/db/generated/member.sql.go
@@ -89,6 +89,26 @@ func (q *Queries) GetMemberByUserAndWorkspace(ctx context.Context, arg GetMember
return i, err
}
+const getMemberForUpdate = `-- name: GetMemberForUpdate :one
+SELECT id, workspace_id, user_id, role, created_at, pinned_at FROM member WHERE id = $1 FOR UPDATE
+`
+
+// Locks a member row for a role change, so concurrent changes to the same
+// member apply one after the other and each re-checks the role it starts from.
+func (q *Queries) GetMemberForUpdate(ctx context.Context, id pgtype.UUID) (Member, error) {
+ row := q.db.QueryRow(ctx, getMemberForUpdate, id)
+ var i Member
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.UserID,
+ &i.Role,
+ &i.CreatedAt,
+ &i.PinnedAt,
+ )
+ return i, err
+}
+
const getRealtimeMemberships = `-- name: GetRealtimeMemberships :many
SELECT m.user_id, m.workspace_id
FROM member m
@@ -97,6 +117,7 @@ JOIN (
unnest($2::uuid[]) AS workspace_id
) AS requested
ON m.user_id = requested.user_id AND m.workspace_id = requested.workspace_id
+WHERE m.role <> 'guest'
`
type GetRealtimeMembershipsParams struct {
@@ -109,6 +130,8 @@ type GetRealtimeMembershipsRow struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
+// Guests (MUL-9420) get no realtime stream: workspace fanout is not narrowed
+// to their projects, so a socket that becomes a guest's is closed.
func (q *Queries) GetRealtimeMemberships(ctx context.Context, arg GetRealtimeMembershipsParams) ([]GetRealtimeMembershipsRow, error) {
rows, err := q.db.Query(ctx, getRealtimeMemberships, arg.UserIds, arg.WorkspaceIds)
if err != nil {
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 954aeacac8..65174aa917 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1512,6 +1512,13 @@ type MemberDelegationDay struct {
ActivityDate pgtype.Date `json:"activity_date"`
}
+type MemberSearchAccess struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ ChangedXid pgtype.Uint64 `json:"changed_xid"`
+ ChangedAt pgtype.Timestamptz `json:"changed_at"`
+}
+
type NotificationPreference struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -2223,6 +2230,7 @@ type WorkspaceInvitation struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
}
type WorkspaceMcpServer struct {
diff --git a/server/pkg/db/generated/project_member.sql.go b/server/pkg/db/generated/project_member.sql.go
index c8a05f63ee..dd50246b86 100644
--- a/server/pkg/db/generated/project_member.sql.go
+++ b/server/pkg/db/generated/project_member.sql.go
@@ -61,6 +61,110 @@ func (q *Queries) AddProjectMembers(ctx context.Context, arg AddProjectMembersPa
return items, nil
}
+const addUserToProjects = `-- name: AddUserToProjects :many
+INSERT INTO project_member (workspace_id, project_id, user_id, added_by)
+SELECT p.workspace_id, p.id, $1::uuid, $2::uuid
+FROM project p
+WHERE p.workspace_id = $3
+ AND p.id = ANY($4::uuid[])
+ON CONFLICT (project_id, user_id) DO NOTHING
+RETURNING workspace_id, project_id, user_id, added_by, created_at
+`
+
+type AddUserToProjectsParams struct {
+ UserID pgtype.UUID `json:"user_id"`
+ AddedBy pgtype.UUID `json:"added_by"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
+}
+
+// A guest's (MUL-9420) projects. Unlike AddProjectMembers this does not
+// require a member row, so an invitation's projects can be written in the
+// same transaction that creates the member.
+func (q *Queries) AddUserToProjects(ctx context.Context, arg AddUserToProjectsParams) ([]ProjectMember, error) {
+ rows, err := q.db.Query(ctx, addUserToProjects,
+ arg.UserID,
+ arg.AddedBy,
+ arg.WorkspaceID,
+ arg.ProjectIds,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ProjectMember{}
+ for rows.Next() {
+ var i ProjectMember
+ if err := rows.Scan(
+ &i.WorkspaceID,
+ &i.ProjectID,
+ &i.UserID,
+ &i.AddedBy,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const countGuestsNotInProject = `-- name: CountGuestsNotInProject :one
+SELECT count(*)::bigint FROM member m
+WHERE m.workspace_id = $1
+ AND m.role = 'guest'
+ AND m.user_id = ANY($2::uuid[])
+ AND NOT EXISTS (
+ SELECT 1 FROM project_member pm
+ WHERE pm.project_id = $3
+ AND pm.user_id = m.user_id
+ )
+`
+
+type CountGuestsNotInProjectParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserIds []pgtype.UUID `json:"user_ids"`
+ ProjectID pgtype.UUID `json:"project_id"`
+}
+
+// How many of user_ids are guests (MUL-9420) of the workspace who are not
+// members of project_id yet: adding them shares another project with a
+// guest. A project that does not exist yet (the nil uuid) has no members.
+func (q *Queries) CountGuestsNotInProject(ctx context.Context, arg CountGuestsNotInProjectParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countGuestsNotInProject, arg.WorkspaceID, arg.UserIds, arg.ProjectID)
+ var column_1 int64
+ err := row.Scan(&column_1)
+ return column_1, err
+}
+
+const countProjectsUserIsNotMemberOf = `-- name: CountProjectsUserIsNotMemberOf :one
+SELECT count(*)::bigint FROM unnest($1::uuid[]) AS requested(id)
+WHERE NOT EXISTS (
+ SELECT 1 FROM project_member pm
+ WHERE pm.workspace_id = $2
+ AND pm.user_id = $3
+ AND pm.project_id = requested.id
+)
+`
+
+type CountProjectsUserIsNotMemberOfParams struct {
+ ProjectIds []pgtype.UUID `json:"project_ids"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// How many of project_ids the user is not a member of yet: setting a guest's
+// projects to these adds that many (MUL-9420).
+func (q *Queries) CountProjectsUserIsNotMemberOf(ctx context.Context, arg CountProjectsUserIsNotMemberOfParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countProjectsUserIsNotMemberOf, arg.ProjectIds, arg.WorkspaceID, arg.UserID)
+ var column_1 int64
+ err := row.Scan(&column_1)
+ return column_1, err
+}
+
const deleteProjectMember = `-- name: DeleteProjectMember :execrows
DELETE FROM project_member
WHERE project_id = $1
@@ -170,6 +274,73 @@ func (q *Queries) GetProjectAccessManager(ctx context.Context, arg GetProjectAcc
return user_id, err
}
+const listAgentIDsSeenByGuest = `-- name: ListAgentIDsSeenByGuest :many
+WITH visible_issue AS (
+ SELECT i.id, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id
+ FROM issue i
+ JOIN project_member pm ON pm.project_id = i.project_id
+ WHERE pm.workspace_id = $1
+ AND pm.user_id = $2
+ AND i.workspace_id = $1
+)
+SELECT v.assignee_id::uuid AS agent_id FROM visible_issue v
+WHERE v.assignee_type = 'agent' AND v.assignee_id IS NOT NULL
+UNION
+SELECT v.creator_id FROM visible_issue v WHERE v.creator_type = 'agent'
+UNION
+SELECT c.author_id FROM comment c JOIN visible_issue v ON v.id = c.issue_id
+WHERE c.author_type = 'agent'
+UNION
+SELECT cr.actor_id FROM comment_reaction cr
+JOIN comment c ON c.id = cr.comment_id
+JOIN visible_issue v ON v.id = c.issue_id
+WHERE cr.actor_type = 'agent'
+UNION
+SELECT r.actor_id FROM issue_reaction r JOIN visible_issue v ON v.id = r.issue_id
+WHERE r.actor_type = 'agent'
+UNION
+SELECT a.actor_id FROM activity_log a JOIN visible_issue v ON v.id = a.issue_id
+WHERE a.actor_type = 'agent' AND a.actor_id IS NOT NULL
+UNION
+SELECT s.user_id FROM issue_subscriber s JOIN visible_issue v ON v.id = s.issue_id
+WHERE s.user_type = 'agent'
+UNION
+SELECT p.lead_id FROM project p
+JOIN project_member pm ON pm.project_id = p.id
+WHERE pm.workspace_id = $1
+ AND pm.user_id = $2
+ AND p.lead_type = 'agent' AND p.lead_id IS NOT NULL
+`
+
+type ListAgentIDsSeenByGuestParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// The agents a guest (MUL-9420) meets in its projects: as an issue's
+// assignee or creator, a comment's author, a reaction, an activity entry, a
+// subscriber or a project lead. A guest is shown only these, to render their
+// names and avatars, not the workspace's agent directory.
+func (q *Queries) ListAgentIDsSeenByGuest(ctx context.Context, arg ListAgentIDsSeenByGuestParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listAgentIDsSeenByGuest, arg.WorkspaceID, arg.UserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var agent_id pgtype.UUID
+ if err := rows.Scan(&agent_id); err != nil {
+ return nil, err
+ }
+ items = append(items, agent_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listAutopilotRunProjectIDs = `-- name: ListAutopilotRunProjectIDs :many
SELECT r.id, a.project_id
FROM autopilot_run r
@@ -202,6 +373,76 @@ func (q *Queries) ListAutopilotRunProjectIDs(ctx context.Context, ids []pgtype.U
return items, nil
}
+const listGuestProjects = `-- name: ListGuestProjects :many
+SELECT pm.user_id, pm.project_id
+FROM project_member pm
+JOIN member m ON m.workspace_id = pm.workspace_id AND m.user_id = pm.user_id
+WHERE pm.workspace_id = $1 AND m.role = 'guest'
+ORDER BY pm.created_at, pm.project_id
+`
+
+type ListGuestProjectsRow struct {
+ UserID pgtype.UUID `json:"user_id"`
+ ProjectID pgtype.UUID `json:"project_id"`
+}
+
+// Every guest's projects in a workspace, for the members list.
+func (q *Queries) ListGuestProjects(ctx context.Context, workspaceID pgtype.UUID) ([]ListGuestProjectsRow, error) {
+ rows, err := q.db.Query(ctx, listGuestProjects, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListGuestProjectsRow{}
+ for rows.Next() {
+ var i ListGuestProjectsRow
+ if err := rows.Scan(&i.UserID, &i.ProjectID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listHiddenProjectIDsForGuest = `-- name: ListHiddenProjectIDsForGuest :many
+SELECT p.id FROM project p
+WHERE p.workspace_id = $1
+ AND NOT EXISTS (
+ SELECT 1 FROM project_member pm
+ WHERE pm.project_id = p.id AND pm.user_id = $2
+ )
+`
+
+type ListHiddenProjectIDsForGuestParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// Every project a guest (MUL-9420) cannot see: all but the ones it is a
+// member of, whatever their visibility.
+func (q *Queries) ListHiddenProjectIDsForGuest(ctx context.Context, arg ListHiddenProjectIDsForGuestParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listHiddenProjectIDsForGuest, arg.WorkspaceID, arg.UserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listHiddenProjectIDsForUser = `-- name: ListHiddenProjectIDsForUser :many
SELECT p.id FROM project p
WHERE p.workspace_id = $1
@@ -415,6 +656,58 @@ func (q *Queries) ListProjectMembers(ctx context.Context, arg ListProjectMembers
return items, nil
}
+const listWorkspaceProjectIDs = `-- name: ListWorkspaceProjectIDs :many
+SELECT id FROM project
+WHERE workspace_id = $1 AND id = ANY($2::uuid[])
+`
+
+type ListWorkspaceProjectIDsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
+}
+
+// The ids among project_ids that are projects of this workspace.
+func (q *Queries) ListWorkspaceProjectIDs(ctx context.Context, arg ListWorkspaceProjectIDsParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listWorkspaceProjectIDs, arg.WorkspaceID, arg.ProjectIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const removeUserFromProjectsExcept = `-- name: RemoveUserFromProjectsExcept :execrows
+DELETE FROM project_member
+WHERE workspace_id = $1
+ AND user_id = $2
+ AND NOT (project_id = ANY($3::uuid[]))
+`
+
+type RemoveUserFromProjectsExceptParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ KeepProjectIds []pgtype.UUID `json:"keep_project_ids"`
+}
+
+func (q *Queries) RemoveUserFromProjectsExcept(ctx context.Context, arg RemoveUserFromProjectsExceptParams) (int64, error) {
+ result, err := q.db.Exec(ctx, removeUserFromProjectsExcept, arg.WorkspaceID, arg.UserID, arg.KeepProjectIds)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const touchProjectSearchIndexEntries = `-- name: TouchProjectSearchIndexEntries :exec
INSERT INTO search_index_change (entity_type, entity_id, workspace_id, change_xid, changed_at)
SELECT 'project', p.id, p.workspace_id, pg_current_xact_id(), now()
diff --git a/server/pkg/db/generated/search_index.sql.go b/server/pkg/db/generated/search_index.sql.go
index fad97238c5..1947eb4c6d 100644
--- a/server/pkg/db/generated/search_index.sql.go
+++ b/server/pkg/db/generated/search_index.sql.go
@@ -11,6 +11,15 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const deleteWorkspaceMemberSearchAccess = `-- name: DeleteWorkspaceMemberSearchAccess :exec
+DELETE FROM member_search_access WHERE workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceMemberSearchAccess(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceMemberSearchAccess, workspaceID)
+ return err
+}
+
const deleteWorkspaceSearchIndexChanges = `-- name: DeleteWorkspaceSearchIndexChanges :exec
DELETE FROM search_index_change WHERE workspace_id = $1
`
@@ -37,7 +46,7 @@ WITH ws AS (SELECT $1::uuid AS id, $2::uuid[] AS hidden),
visible_issue AS (
SELECT i.id, i.title, i.description FROM issue i, ws
WHERE i.workspace_id = ws.id
- AND (ws.hidden IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(ws.hidden)))
+ AND (ws.hidden IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(ws.hidden)))
),
visible_comment AS (
SELECT c.content FROM comment c
@@ -479,6 +488,27 @@ func (q *Queries) ListSearchIndexProjectsByIDs(ctx context.Context, arg ListSear
return items, nil
}
+const markSearchAccessChanged = `-- name: MarkSearchAccessChanged :exec
+INSERT INTO member_search_access (workspace_id, user_id, changed_xid, changed_at)
+VALUES ($1, $2, pg_current_xact_id(), now())
+ON CONFLICT (workspace_id, user_id) DO UPDATE
+ SET changed_xid = EXCLUDED.changed_xid,
+ changed_at = EXCLUDED.changed_at
+`
+
+type MarkSearchAccessChangedParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// Records that this transaction changed what the user can see in the
+// workspace without rewriting the content (MUL-9420), so local search copies
+// built before it are rebuilt.
+func (q *Queries) MarkSearchAccessChanged(ctx context.Context, arg MarkSearchAccessChangedParams) error {
+ _, err := q.db.Exec(ctx, markSearchAccessChanged, arg.WorkspaceID, arg.UserID)
+ return err
+}
+
const pruneSearchIndexChanges = `-- name: PruneSearchIndexChanges :one
WITH doomed AS (
SELECT sic.entity_type, sic.entity_id
@@ -518,6 +548,30 @@ func (q *Queries) PruneSearchIndexChanges(ctx context.Context, arg PruneSearchIn
return deleted_count, err
}
+const searchAccessChangedAfter = `-- name: SearchAccessChangedAfter :one
+SELECT EXISTS (
+ SELECT 1 FROM member_search_access
+ WHERE workspace_id = $1
+ AND user_id = $2
+ AND NOT pg_visible_in_snapshot(changed_xid, ($3::text)::pg_snapshot)
+)::bool AS changed
+`
+
+type SearchAccessChangedAfterParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ SinceSnapshot string `json:"since_snapshot"`
+}
+
+// Whether the user's access in the workspace was changed by a transaction the
+// since snapshot does not include.
+func (q *Queries) SearchAccessChangedAfter(ctx context.Context, arg SearchAccessChangedAfterParams) (bool, error) {
+ row := q.db.QueryRow(ctx, searchAccessChangedAfter, arg.WorkspaceID, arg.UserID, arg.SinceSnapshot)
+ var changed bool
+ err := row.Scan(&changed)
+ return changed, err
+}
+
const searchIndexSinceIsPruned = `-- name: SearchIndexSinceIsPruned :one
SELECT EXISTS (
SELECT 1 FROM search_index_prune_mark
diff --git a/server/pkg/db/generated/subscriber.sql.go b/server/pkg/db/generated/subscriber.sql.go
index 30c0601b19..4b5e8a13d0 100644
--- a/server/pkg/db/generated/subscriber.sql.go
+++ b/server/pkg/db/generated/subscriber.sql.go
@@ -347,7 +347,7 @@ WHERE i.workspace_id = $1
AND s.user_id = $2
AND s.unsubscribed_at IS NULL
-- MUL-8472: private projects the caller cannot see.
- AND ($3::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($3::uuid[])))
+ AND ($3::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])))
`
type ListSubscribedIssueIDsParams struct {
diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.go
index 4d2fc51c9b..46ad210679 100644
--- a/server/pkg/db/generated/wakeup.sql.go
+++ b/server/pkg/db/generated/wakeup.sql.go
@@ -1071,7 +1071,7 @@ SELECT w.issue_id,w.id,w.agent_id,w.paused_reason
FROM issue_wakeup w JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id
WHERE w.workspace_id= $1 AND NOT w.enabled AND w.paused_reason IN ('loop','rate','max_fires')
-- MUL-8472: private projects the caller cannot see.
- AND ($2::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($2::uuid[])))
+ AND ($2::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($2::uuid[])))
AND i.status NOT IN ('done','cancelled')
AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))
ORDER BY w.updated_at DESC LIMIT 200
@@ -1391,7 +1391,7 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id
LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY($1::uuid[])
WHERE w.workspace_id= $2 AND w.enabled
-- MUL-8472: private projects the caller cannot see.
- AND ($3::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($3::uuid[])))
+ AND ($3::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($3::uuid[])))
AND i.status NOT IN ('done','cancelled')
AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))
)
diff --git a/server/pkg/db/generated/workspace_wakeup.sql.go b/server/pkg/db/generated/workspace_wakeup.sql.go
index 9bb696e106..70ad67acf7 100644
--- a/server/pkg/db/generated/workspace_wakeup.sql.go
+++ b/server/pkg/db/generated/workspace_wakeup.sql.go
@@ -50,7 +50,7 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id
) r ON true
WHERE w.workspace_id= $4 AND w.system_rule IS NULL
-- MUL-8472: private projects the caller cannot see.
- AND ($5::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($5::uuid[])))
+ AND ($5::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($5::uuid[])))
UNION ALL
-- The child-done system rule of each open parent that still waits for a
-- sub-issue: every child when unstaged, else its lowest unfinished stage.
@@ -90,7 +90,7 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id
) sr ON true
WHERE w.workspace_id= $4 AND w.system_rule IS NOT NULL AND agg.open_count>0
-- MUL-8472: private projects the caller cannot see.
- AND ($5::uuid[] IS NULL OR p.project_id IS NULL OR NOT (p.project_id = ANY($5::uuid[])))
+ AND ($5::uuid[] IS NULL OR NOT (COALESCE(p.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY($5::uuid[])))
AND p.status NOT IN ('done','cancelled')
AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=p.workspace_id AND s.key=p.status AND s.category IN ('done','closed'))
), classified AS (
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index 6a2c931bc9..964b059ad7 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -94,6 +94,9 @@ WHERE comment_id = @comment_id AND workspace_id = @workspace_id
RETURNING url;
-- name: LinkAttachmentsToComment :exec
+-- An unbound upload is a draft and joins only its own uploader's comment
+-- (MUL-9420): a guest's file taken off its comment must not be adoptable by
+-- anyone else who learns its id.
UPDATE attachment
SET comment_id = sqlc.arg(comment_id),
issue_id = sqlc.arg(issue_id)
@@ -103,16 +106,31 @@ WHERE workspace_id = sqlc.arg(workspace_id)
AND chat_session_id IS NULL
AND chat_message_id IS NULL
AND task_id IS NULL
+ AND uploader_type = sqlc.arg(uploader_type)
+ AND uploader_id = sqlc.arg(uploader_id)
))
AND comment_id IS NULL
AND source_context_id IS NULL
AND id = ANY(sqlc.arg(attachment_ids)::uuid[]);
-- name: ReplaceCommentAttachments :execrows
+-- A file removed from the comment stays an issue attachment, except a guest's
+-- (MUL-9420): a guest attaches files only through its comments, so its file
+-- goes back to being its unbound draft rather than staying on the issue.
UPDATE attachment
SET comment_id = CASE
WHEN id = ANY(sqlc.arg(attachment_ids)::uuid[]) THEN $1
ELSE NULL
+END,
+issue_id = CASE
+ WHEN id = ANY(sqlc.arg(attachment_ids)::uuid[]) THEN issue_id
+ WHEN uploader_type = 'member' AND EXISTS (
+ SELECT 1 FROM member m
+ WHERE m.workspace_id = attachment.workspace_id
+ AND m.user_id = attachment.uploader_id
+ AND m.role = 'guest'
+ ) THEN NULL
+ ELSE issue_id
END
WHERE issue_id = $2
AND source_context_id IS NULL
@@ -121,6 +139,24 @@ WHERE issue_id = $2
OR (comment_id IS NULL AND id = ANY(sqlc.arg(attachment_ids)::uuid[]))
);
+-- name: BindUploaderDraftAttachmentsToIssue :execrows
+-- A comment edit's own drafts: attachments the editor uploaded that are not
+-- bound to anything yet (a guest's uploads stay unbound until a comment takes
+-- them, MUL-9420) join the comment's issue, so ReplaceCommentAttachments can
+-- link them in the same transaction.
+UPDATE attachment
+SET issue_id = sqlc.arg(issue_id)
+WHERE workspace_id = sqlc.arg(workspace_id)
+ AND id = ANY(sqlc.arg(attachment_ids)::uuid[])
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_session_id IS NULL
+ AND chat_message_id IS NULL
+ AND task_id IS NULL
+ AND source_context_id IS NULL
+ AND uploader_type = sqlc.arg(uploader_type)
+ AND uploader_id = sqlc.arg(uploader_id);
+
-- name: LinkAttachmentsToChatMessage :many
UPDATE attachment
SET chat_message_id = sqlc.arg(chat_message_id),
@@ -208,6 +244,7 @@ FOR UPDATE;
-- Like issue updates, comment creation locks ownerless uploads before the
-- issue row. Once it takes the issue, it locks existing issue children below.
-- This keeps both upload adoption and owner-first deletion in the same order.
+-- Only the comment author's own uploads qualify (see LinkAttachmentsToComment).
SELECT id FROM attachment
WHERE workspace_id = sqlc.arg(workspace_id)
AND issue_id IS NULL
@@ -216,10 +253,20 @@ WHERE workspace_id = sqlc.arg(workspace_id)
AND chat_message_id IS NULL
AND task_id IS NULL
AND source_context_id IS NULL
+ AND uploader_type = sqlc.arg(uploader_type)
+ AND uploader_id = sqlc.arg(uploader_id)
AND id = ANY(sqlc.arg(attachment_ids)::uuid[])
ORDER BY id
FOR UPDATE;
+-- name: ListCommentAttachmentIDsAmong :many
+-- Which of attachment_ids are attached to the comment: an edit checks that
+-- it got every file it asked for before committing.
+SELECT id FROM attachment
+WHERE comment_id = sqlc.arg(comment_id)
+ AND workspace_id = sqlc.arg(workspace_id)
+ AND id = ANY(sqlc.arg(attachment_ids)::uuid[]);
+
-- name: LockAttachmentsForCommentLink :many
-- CreateComment binds attachments in the transaction that created the comment,
-- after the CreateComment statement has taken the issue row: issue -> comment
diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sql
index 7a1b2c9142..127505fb9a 100644
--- a/server/pkg/db/queries/github.sql
+++ b/server/pkg/db/queries/github.sql
@@ -218,7 +218,7 @@ JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id
JOIN issue i ON i.id = ipr.issue_id
WHERE pr.workspace_id = sqlc.arg('workspace_id')
AND i.workspace_id = sqlc.arg('workspace_id')
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
UNION ALL
SELECT
ipr.issue_id,
@@ -229,7 +229,7 @@ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id
JOIN issue i ON i.id = ipr.issue_id
WHERE pr.workspace_id = sqlc.arg('workspace_id')
AND i.workspace_id = sqlc.arg('workspace_id')
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
ORDER BY pr_created_at DESC;
-- name: GetIssueReviewHeadSha :one
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index f9c50ab98a..df1e75803a 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -20,7 +20,7 @@ WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND
-- whose time has passed is listed again and keeps snoozed_until, which is
-- how the client tells an issue that came back on its own.
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR iss.project_id IS NULL OR NOT (iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
-- Newest first by when the row arrived or came back (returned_at), the order
-- idx_inbox_active_shown keeps. The
-- inbox keeps only its newest rows (inbox.ActiveLimit); inbox.Trimmer archives
@@ -64,7 +64,7 @@ WITH eligible_archived AS MATERIALIZED (
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1
@@ -269,7 +269,7 @@ WHERE i.workspace_id = sqlc.arg('workspace_id')
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
));
-- name: CountUnreadInboxByWorkspace :many
@@ -462,7 +462,7 @@ FROM (
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
))
GROUP BY i.issue_id
) g
@@ -490,8 +490,8 @@ SELECT count(*) > 0 FROM (
WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3
AND i.archived = false
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR iss.project_id IS NULL
- OR NOT (iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL
+ OR NOT (COALESCE(iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
OFFSET sqlc.arg('keep')::int
LIMIT 1
@@ -516,8 +516,8 @@ WITH boundary AS MATERIALIZED (
AND b.recipient_id = sqlc.arg('recipient_id')
AND b.archived = false
AND (b.snoozed_until IS NULL OR b.snoozed_until <= now())
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR b_iss.project_id IS NULL
- OR NOT (b_iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL
+ OR NOT (COALESCE(b_iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
ORDER BY GREATEST(b.created_at, b.returned_at) DESC, b.id DESC
OFFSET sqlc.arg('keep')::int - 1
LIMIT 1
@@ -529,8 +529,8 @@ WITH boundary AS MATERIALIZED (
AND o.recipient_id = sqlc.arg('recipient_id')
AND o.archived = false
AND (o.snoozed_until IS NULL OR o.snoozed_until <= now())
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR o_iss.project_id IS NULL
- OR NOT (o_iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL
+ OR NOT (COALESCE(o_iss.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (GREATEST(o.created_at, o.returned_at), o.id) < (boundary.shown_at, boundary.id)
-- An issue back from a snooze whose newest row does not carry the
-- return yet (written by an older server, or not normalized) ranks too
diff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sql
index cbfd6bc9a8..dc7c019d56 100644
--- a/server/pkg/db/queries/inbox_archive.sql
+++ b/server/pkg/db/queries/inbox_archive.sql
@@ -32,7 +32,7 @@ WITH base AS MATERIALIZED (
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
))
AND (sqlc.narg(group_id)::uuid IS NULL OR i.issue_id = sqlc.narg(group_id)::uuid
OR (i.issue_id IS NULL AND i.id = sqlc.narg(group_id)::uuid))
@@ -147,7 +147,7 @@ WITH base AS MATERIALIZED (
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = i.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
))
AND (i.issue_id IS NULL OR NOT EXISTS (
SELECT 1 FROM inbox_item active
diff --git a/server/pkg/db/queries/invitation.sql b/server/pkg/db/queries/invitation.sql
index bfddcd2010..4cf46a8638 100644
--- a/server/pkg/db/queries/invitation.sql
+++ b/server/pkg/db/queries/invitation.sql
@@ -1,6 +1,6 @@
-- name: CreateInvitation :one
-INSERT INTO workspace_invitation (id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, expires_at)
-VALUES ($1, $2, $3, $4, $5, $6, $7)
+INSERT INTO workspace_invitation (id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, expires_at, project_ids)
+VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE(sqlc.narg('project_ids')::uuid[], '{}'))
RETURNING *;
-- name: GetInvitation :one
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index eab3b2ddff..5597533d80 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -19,7 +19,7 @@ WHERE i.workspace_id = $1
AND (sqlc.narg('created_by_user_id')::uuid IS NULL OR (i.creator_type = 'member' AND i.creator_id = sqlc.narg('created_by_user_id')) OR i.requester_user_id = sqlc.narg('created_by_user_id'))
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (sqlc.narg('scheduled')::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))
AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)
AND (
@@ -542,7 +542,7 @@ WHERE i.workspace_id = $1
AND (sqlc.narg('created_by_user_id')::uuid IS NULL OR (i.creator_type = 'member' AND i.creator_id = sqlc.narg('created_by_user_id')) OR i.requester_user_id = sqlc.narg('created_by_user_id'))
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)
-- properties_filter is a jsonb array of groups, each group an array of
-- patterns (built by parsePropertiesFilterParam): the issue must match at
@@ -647,7 +647,7 @@ WHERE i.workspace_id = $1
AND (sqlc.narg('created_by_user_id')::uuid IS NULL OR (i.creator_type = 'member' AND i.creator_id = sqlc.narg('created_by_user_id')) OR i.requester_user_id = sqlc.narg('created_by_user_id'))
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (sqlc.narg('scheduled')::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))
AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)
AND (
@@ -741,7 +741,7 @@ FROM issue
WHERE workspace_id = $1
AND parent_issue_id IS NOT NULL
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR project_id IS NULL OR NOT (project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
GROUP BY parent_issue_id;
-- SearchIssues: moved to handler (dynamic SQL for multi-word search support).
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
index cbfff065fc..3f0dcf0a83 100644
--- a/server/pkg/db/queries/issue_label.sql
+++ b/server/pkg/db/queries/issue_label.sql
@@ -6,7 +6,7 @@ SELECT l.*,
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = x.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
)))
WHEN 'agent' THEN (SELECT COUNT(*) FROM agent_to_label x WHERE x.label_id = l.id)
WHEN 'skill' THEN (SELECT COUNT(*) FROM skill_to_label x WHERE x.label_id = l.id)
diff --git a/server/pkg/db/queries/issue_unread.sql b/server/pkg/db/queries/issue_unread.sql
index e66c0ad34b..e89a4fcd2f 100644
--- a/server/pkg/db/queries/issue_unread.sql
+++ b/server/pkg/db/queries/issue_unread.sql
@@ -44,7 +44,7 @@ WHERE u.workspace_id = sqlc.arg(workspace_id)
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT EXISTS (
SELECT 1 FROM issue hidden_issue
WHERE hidden_issue.id = u.issue_id
- AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])
+ AND COALESCE(hidden_issue.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])
))
AND (
sqlc.narg(before_created_at)::timestamptz IS NULL
diff --git a/server/pkg/db/queries/member.sql b/server/pkg/db/queries/member.sql
index 98c1f945c7..e102b783d4 100644
--- a/server/pkg/db/queries/member.sql
+++ b/server/pkg/db/queries/member.sql
@@ -23,7 +23,10 @@ JOIN (
SELECT unnest(sqlc.arg(user_ids)::uuid[]) AS user_id,
unnest(sqlc.arg(workspace_ids)::uuid[]) AS workspace_id
) AS requested
- ON m.user_id = requested.user_id AND m.workspace_id = requested.workspace_id;
+ ON m.user_id = requested.user_id AND m.workspace_id = requested.workspace_id
+-- Guests (MUL-9420) get no realtime stream: workspace fanout is not narrowed
+-- to their projects, so a socket that becomes a guest's is closed.
+WHERE m.role <> 'guest';
-- name: CreateMember :one
INSERT INTO member (workspace_id, user_id, role)
@@ -35,6 +38,11 @@ UPDATE member SET role = $2
WHERE id = $1
RETURNING *;
+-- name: GetMemberForUpdate :one
+-- Locks a member row for a role change, so concurrent changes to the same
+-- member apply one after the other and each re-checks the role it starts from.
+SELECT * FROM member WHERE id = $1 FOR UPDATE;
+
-- name: DeleteMember :exec
DELETE FROM member WHERE id = $1;
diff --git a/server/pkg/db/queries/project_member.sql b/server/pkg/db/queries/project_member.sql
index 0f868491ef..969f6f3a11 100644
--- a/server/pkg/db/queries/project_member.sql
+++ b/server/pkg/db/queries/project_member.sql
@@ -15,6 +15,16 @@ WHERE p.workspace_id = sqlc.arg('workspace_id')
WHERE pm.project_id = p.id AND pm.user_id = sqlc.arg('user_id')
);
+-- name: ListHiddenProjectIDsForGuest :many
+-- Every project a guest (MUL-9420) cannot see: all but the ones it is a
+-- member of, whatever their visibility.
+SELECT p.id FROM project p
+WHERE p.workspace_id = sqlc.arg('workspace_id')
+ AND NOT EXISTS (
+ SELECT 1 FROM project_member pm
+ WHERE pm.project_id = p.id AND pm.user_id = sqlc.arg('user_id')
+ );
+
-- name: ListPrivateProjectAudience :many
-- Realtime fanout for private-project events: each private project with its
-- member user ids (NULL user_id when the project has no members yet).
@@ -46,6 +56,37 @@ WHERE m.workspace_id = sqlc.arg('workspace_id')
ON CONFLICT (project_id, user_id) DO NOTHING
RETURNING *;
+-- name: ListWorkspaceProjectIDs :many
+-- The ids among project_ids that are projects of this workspace.
+SELECT id FROM project
+WHERE workspace_id = sqlc.arg('workspace_id') AND id = ANY(sqlc.arg('project_ids')::uuid[]);
+
+-- name: ListGuestProjects :many
+-- Every guest's projects in a workspace, for the members list.
+SELECT pm.user_id, pm.project_id
+FROM project_member pm
+JOIN member m ON m.workspace_id = pm.workspace_id AND m.user_id = pm.user_id
+WHERE pm.workspace_id = $1 AND m.role = 'guest'
+ORDER BY pm.created_at, pm.project_id;
+
+-- name: AddUserToProjects :many
+-- A guest's (MUL-9420) projects. Unlike AddProjectMembers this does not
+-- require a member row, so an invitation's projects can be written in the
+-- same transaction that creates the member.
+INSERT INTO project_member (workspace_id, project_id, user_id, added_by)
+SELECT p.workspace_id, p.id, sqlc.arg('user_id')::uuid, sqlc.narg('added_by')::uuid
+FROM project p
+WHERE p.workspace_id = sqlc.arg('workspace_id')
+ AND p.id = ANY(sqlc.arg('project_ids')::uuid[])
+ON CONFLICT (project_id, user_id) DO NOTHING
+RETURNING *;
+
+-- name: RemoveUserFromProjectsExcept :execrows
+DELETE FROM project_member
+WHERE workspace_id = sqlc.arg('workspace_id')
+ AND user_id = sqlc.arg('user_id')
+ AND NOT (project_id = ANY(sqlc.arg('keep_project_ids')::uuid[]));
+
-- name: DeleteProjectMember :execrows
DELETE FROM project_member
WHERE project_id = sqlc.arg('project_id')
@@ -126,3 +167,69 @@ SELECT r.id, a.project_id
FROM autopilot_run r
JOIN autopilot a ON a.id = r.autopilot_id
WHERE r.id = ANY(sqlc.arg('ids')::uuid[]);
+
+-- name: CountProjectsUserIsNotMemberOf :one
+-- How many of project_ids the user is not a member of yet: setting a guest's
+-- projects to these adds that many (MUL-9420).
+SELECT count(*)::bigint FROM unnest(sqlc.arg('project_ids')::uuid[]) AS requested(id)
+WHERE NOT EXISTS (
+ SELECT 1 FROM project_member pm
+ WHERE pm.workspace_id = sqlc.arg('workspace_id')
+ AND pm.user_id = sqlc.arg('user_id')
+ AND pm.project_id = requested.id
+);
+
+-- name: CountGuestsNotInProject :one
+-- How many of user_ids are guests (MUL-9420) of the workspace who are not
+-- members of project_id yet: adding them shares another project with a
+-- guest. A project that does not exist yet (the nil uuid) has no members.
+SELECT count(*)::bigint FROM member m
+WHERE m.workspace_id = sqlc.arg('workspace_id')
+ AND m.role = 'guest'
+ AND m.user_id = ANY(sqlc.arg('user_ids')::uuid[])
+ AND NOT EXISTS (
+ SELECT 1 FROM project_member pm
+ WHERE pm.project_id = sqlc.arg('project_id')
+ AND pm.user_id = m.user_id
+ );
+
+-- name: ListAgentIDsSeenByGuest :many
+-- The agents a guest (MUL-9420) meets in its projects: as an issue's
+-- assignee or creator, a comment's author, a reaction, an activity entry, a
+-- subscriber or a project lead. A guest is shown only these, to render their
+-- names and avatars, not the workspace's agent directory.
+WITH visible_issue AS (
+ SELECT i.id, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id
+ FROM issue i
+ JOIN project_member pm ON pm.project_id = i.project_id
+ WHERE pm.workspace_id = sqlc.arg('workspace_id')
+ AND pm.user_id = sqlc.arg('user_id')
+ AND i.workspace_id = sqlc.arg('workspace_id')
+)
+SELECT v.assignee_id::uuid AS agent_id FROM visible_issue v
+WHERE v.assignee_type = 'agent' AND v.assignee_id IS NOT NULL
+UNION
+SELECT v.creator_id FROM visible_issue v WHERE v.creator_type = 'agent'
+UNION
+SELECT c.author_id FROM comment c JOIN visible_issue v ON v.id = c.issue_id
+WHERE c.author_type = 'agent'
+UNION
+SELECT cr.actor_id FROM comment_reaction cr
+JOIN comment c ON c.id = cr.comment_id
+JOIN visible_issue v ON v.id = c.issue_id
+WHERE cr.actor_type = 'agent'
+UNION
+SELECT r.actor_id FROM issue_reaction r JOIN visible_issue v ON v.id = r.issue_id
+WHERE r.actor_type = 'agent'
+UNION
+SELECT a.actor_id FROM activity_log a JOIN visible_issue v ON v.id = a.issue_id
+WHERE a.actor_type = 'agent' AND a.actor_id IS NOT NULL
+UNION
+SELECT s.user_id FROM issue_subscriber s JOIN visible_issue v ON v.id = s.issue_id
+WHERE s.user_type = 'agent'
+UNION
+SELECT p.lead_id FROM project p
+JOIN project_member pm ON pm.project_id = p.id
+WHERE pm.workspace_id = sqlc.arg('workspace_id')
+ AND pm.user_id = sqlc.arg('user_id')
+ AND p.lead_type = 'agent' AND p.lead_id IS NOT NULL;
diff --git a/server/pkg/db/queries/search_index.sql b/server/pkg/db/queries/search_index.sql
index aa5ca7baf4..43b2b6e003 100644
--- a/server/pkg/db/queries/search_index.sql
+++ b/server/pkg/db/queries/search_index.sql
@@ -13,7 +13,7 @@ WITH ws AS (SELECT @workspace_id::uuid AS id, sqlc.narg('hidden_project_ids')::u
visible_issue AS (
SELECT i.id, i.title, i.description FROM issue i, ws
WHERE i.workspace_id = ws.id
- AND (ws.hidden IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(ws.hidden)))
+ AND (ws.hidden IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(ws.hidden)))
),
visible_comment AS (
SELECT c.content FROM comment c
@@ -125,3 +125,26 @@ SELECT count(*)::bigint AS deleted_count FROM deleted;
-- name: DeleteWorkspaceSearchIndexChanges :exec
DELETE FROM search_index_change WHERE workspace_id = $1;
+
+-- name: MarkSearchAccessChanged :exec
+-- Records that this transaction changed what the user can see in the
+-- workspace without rewriting the content (MUL-9420), so local search copies
+-- built before it are rebuilt.
+INSERT INTO member_search_access (workspace_id, user_id, changed_xid, changed_at)
+VALUES (@workspace_id, @user_id, pg_current_xact_id(), now())
+ON CONFLICT (workspace_id, user_id) DO UPDATE
+ SET changed_xid = EXCLUDED.changed_xid,
+ changed_at = EXCLUDED.changed_at;
+
+-- name: SearchAccessChangedAfter :one
+-- Whether the user's access in the workspace was changed by a transaction the
+-- since snapshot does not include.
+SELECT EXISTS (
+ SELECT 1 FROM member_search_access
+ WHERE workspace_id = @workspace_id
+ AND user_id = @user_id
+ AND NOT pg_visible_in_snapshot(changed_xid, (@since_snapshot::text)::pg_snapshot)
+)::bool AS changed;
+
+-- name: DeleteWorkspaceMemberSearchAccess :exec
+DELETE FROM member_search_access WHERE workspace_id = $1;
diff --git a/server/pkg/db/queries/subscriber.sql b/server/pkg/db/queries/subscriber.sql
index 9165a0dda3..dd4751021e 100644
--- a/server/pkg/db/queries/subscriber.sql
+++ b/server/pkg/db/queries/subscriber.sql
@@ -310,7 +310,7 @@ WHERE i.workspace_id = sqlc.arg(workspace_id)
AND s.user_id = sqlc.arg(user_id)
AND s.unsubscribed_at IS NULL
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])));
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])));
-- name: IsIssueSubscriber :one
SELECT EXISTS(
diff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sql
index e3786509e7..d5d1cd7d6b 100644
--- a/server/pkg/db/queries/wakeup.sql
+++ b/server/pkg/db/queries/wakeup.sql
@@ -47,7 +47,7 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id
LEFT JOIN agent source ON source.id=w.filter_agent_id AND source.workspace_id=w.workspace_id AND source.id=ANY(@agent_ids::uuid[])
WHERE w.workspace_id= @workspace_id AND w.enabled
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND i.status NOT IN ('done','cancelled')
AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))
)
@@ -287,7 +287,7 @@ SELECT w.issue_id,w.id,w.agent_id,w.paused_reason
FROM issue_wakeup w JOIN issue i ON i.id=w.issue_id AND i.workspace_id=w.workspace_id
WHERE w.workspace_id= @workspace_id AND NOT w.enabled AND w.paused_reason IN ('loop','rate','max_fires')
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND i.status NOT IN ('done','cancelled')
AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=i.workspace_id AND s.key=i.status AND s.category IN ('done','closed'))
ORDER BY w.updated_at DESC LIMIT 200;
diff --git a/server/pkg/db/queries/workspace_wakeup.sql b/server/pkg/db/queries/workspace_wakeup.sql
index 241e4dbb6b..411eb0d40f 100644
--- a/server/pkg/db/queries/workspace_wakeup.sql
+++ b/server/pkg/db/queries/workspace_wakeup.sql
@@ -38,7 +38,7 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id
) r ON true
WHERE w.workspace_id= @workspace_id AND w.system_rule IS NULL
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
UNION ALL
-- The child-done system rule of each open parent that still waits for a
-- sub-issue: every child when unstaged, else its lowest unfinished stage.
@@ -78,7 +78,7 @@ LEFT JOIN "user" actor_user ON actor_user.id=actor_member.user_id
) sr ON true
WHERE w.workspace_id= @workspace_id AND w.system_rule IS NOT NULL AND agg.open_count>0
-- MUL-8472: private projects the caller cannot see.
- AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR p.project_id IS NULL OR NOT (p.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT (COALESCE(p.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND p.status NOT IN ('done','cancelled')
AND NOT EXISTS(SELECT 1 FROM issue_status s WHERE s.workspace_id=p.workspace_id AND s.key=p.status AND s.category IN ('done','closed'))
), classified AS (