Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(autopilot): View/Write permission layer + member access delegation (MUL-3807) (#4695)
Bohan Jiangd970b68ce739
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex ba2aea868e..cbc8de8a9a 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -100,6 +100,7 @@ import type {UpdateAutopilotTriggerRequest,ListAutopilotsResponse,GetAutopilotResponse,+ AutopilotCollaboratorsResponse,ListAutopilotRunsResponse,ListWebhookDeliveriesResponse,WebhookDelivery,@@ -2111,6 +2112,22 @@ export class ApiClient {await this.fetch(`/api/autopilots/${id}`, { method: "DELETE" });}+ // Grant a workspace member explicit write access to the autopilot. Both+ // grant and revoke return the full updated collaborator list so callers can+ // refresh without a second round-trip.+ async grantAutopilotAccess(id: string, userId: string): Promise<AutopilotCollaboratorsResponse> {+ return this.fetch(`/api/autopilots/${id}/collaborators`, {+ method: "POST",+ body: JSON.stringify({ user_id: userId }),+ });+ }++ async revokeAutopilotAccess(id: string, userId: string): Promise<AutopilotCollaboratorsResponse> {+ return this.fetch(`/api/autopilots/${id}/collaborators/${userId}`, {+ method: "DELETE",+ });+ }+async triggerAutopilot(id: string): Promise<AutopilotRun> {return this.fetch(`/api/autopilots/${id}/trigger`, { method: "POST" });}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex d8cc9b2677..3532adb682 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -840,6 +840,10 @@ const AutopilotListItemSchema = z.object({trigger_kinds: z.array(z.string()).optional(),next_run_at: z.string().nullable().optional(),last_run_status: z.string().nullable().optional(),+ // Per-caller write capability; absent on older servers (treated as unknown).+ can_write: z.boolean().optional(),+ // Narrower per-caller access-management capability (detail endpoint only).+ can_manage_access: z.boolean().optional(),}).loose();export const ListAutopilotsResponseSchema = z.object({diff --git a/packages/core/autopilots/mutations.ts b/packages/core/autopilots/mutations.tsindex de56586076..09390b3ba3 100644--- a/packages/core/autopilots/mutations.ts+++ b/packages/core/autopilots/mutations.ts@@ -104,6 +104,30 @@ export function useTriggerAutopilot() {});}+export function useGrantAutopilotAccess() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ autopilotId, userId }: { autopilotId: string; userId: string }) =>+ api.grantAutopilotAccess(autopilotId, userId),+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.autopilotId) });+ },+ });+}++export function useRevokeAutopilotAccess() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ autopilotId, userId }: { autopilotId: string; userId: string }) =>+ api.revokeAutopilotAccess(autopilotId, userId),+ onSettled: (_data, _err, vars) => {+ qc.invalidateQueries({ queryKey: autopilotKeys.detail(wsId, vars.autopilotId) });+ },+ });+}+export function useCreateAutopilotTrigger() {const qc = useQueryClient();const wsId = useWorkspaceId();diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 2f6141a2dc..0d52bdbb47 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -49,6 +49,16 @@ export interface Autopilot {// List endpoint returns []; only the detail endpoint populates this.// Treat undefined as empty on older servers.subscribers?: AutopilotSubscriber[];+ // Whether the requesting user may edit / delete / trigger / manage this+ // autopilot (creator, workspace owner/admin, or a granted collaborator).+ // Present on list and detail responses; absent on older servers — treat+ // undefined as "unknown" rather than "denied" (the server is the gate).+ can_write?: boolean;+ // Whether the requesting user may manage the collaborator (access) list —+ // narrower than can_write: held only by the creator and workspace+ // owners/admins, NOT by granted collaborators. Detail-endpoint-only; absent+ // on older servers (fall back to can_write).+ can_manage_access?: boolean;}export interface WebhookEventFilter {@@ -62,6 +72,19 @@ export interface AutopilotSubscriber {created_at: string;}+// A workspace member explicitly granted write access to an autopilot, on top+// of the implicit "creator ∪ owner/admin" set. Members-only for now.+export interface AutopilotCollaborator {+ user_type: "member";+ user_id: string;+ granted_by: string;+ created_at: string;+}++export interface AutopilotCollaboratorsResponse {+ collaborators: AutopilotCollaborator[];+}+export interface AutopilotTrigger {id: string;autopilot_id: string;@@ -164,6 +187,9 @@ export interface ListAutopilotsResponse {export interface GetAutopilotResponse {autopilot: Autopilot;triggers: AutopilotTrigger[];+ // Members explicitly granted write access. Absent on older servers — treat+ // undefined as an empty list.+ collaborators?: AutopilotCollaborator[];}export interface ListAutopilotRunsResponse {diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 803cce15db..58d4aa6c04 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -132,6 +132,8 @@ export type {AutopilotAssigneeType,AutopilotSubscriber,AutopilotSubscriberInput,+ AutopilotCollaborator,+ AutopilotCollaboratorsResponse,AutopilotTrigger,AutopilotTriggerKind,AutopilotRun,diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxindex 822e2c59ce..bcd2dbce95 100644--- a/packages/views/autopilots/components/autopilot-detail-page.tsx+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -4,7 +4,7 @@ import { useState } from "react";import {Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil,Ban, ChevronDown, ChevronRight,- Webhook, Copy, Check, RotateCw,+ Webhook, Copy, Check, RotateCw, Users,} from "lucide-react";import { useQuery } from "@tanstack/react-query";import { autopilotDetailOptions, autopilotRunsOptions, autopilotRunOptions } from "@multica/core/autopilots/queries";@@ -62,6 +62,7 @@ import type { AgentTask } from "@multica/core/types/agent";import { ReadonlyContent } from "../../editor";import { TranscriptButton } from "../../common/task-transcript";import { AutopilotDialog } from "./autopilot-dialog";+import { ManageAccessDialog } from "./manage-access-dialog";import { WebhookPayloadPreview } from "./webhook-payload-preview";import { WebhookDeliveriesSection } from "./webhook-deliveries-section";import { ProjectIcon } from "../../projects/components/project-icon";@@ -256,7 +257,7 @@ function SkippedRunsGroup({);}-function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autopilotId: string }) {+function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: AutopilotTrigger; autopilotId: string; canWrite: boolean }) {const { t } = useT("autopilots");const deleteTrigger = useDeleteAutopilotTrigger();const rotateToken = useRotateAutopilotTriggerWebhookToken();@@ -329,7 +330,7 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop// — keep it pinned to the row's top-right corner. Without this the// trash icon visually floats above the URL action buttons because the// outer flex uses `items-start`.- const deleteButton = (+ const deleteButton = canWrite ? (<Buttonsize="icon"variant="ghost"@@ -339,7 +340,7 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop><Trash2 className="h-3.5 w-3.5 text-muted-foreground" /></Button>- );+ ) : null;return (<div className="flex items-start gap-3 rounded-md border px-3 py-2">@@ -386,16 +387,18 @@ function TriggerRow({ trigger, autopilotId }: { trigger: AutopilotTrigger; autop>{copied ? <Check className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5 text-muted-foreground" />}</Button>- <Button- size="icon"- variant="ghost"- className="h-7 w-7 shrink-0"- onClick={() => setRotateOpen(true)}- title={t(($) => $.trigger_row.rotate_url)}- disabled={rotateToken.isPending}- >- <RotateCw className={cn("h-3.5 w-3.5 text-muted-foreground", rotateToken.isPending && "animate-spin")} />- </Button>+ {canWrite && (+ <Button+ size="icon"+ variant="ghost"+ className="h-7 w-7 shrink-0"+ onClick={() => setRotateOpen(true)}+ title={t(($) => $.trigger_row.rotate_url)}+ disabled={rotateToken.isPending}+ >+ <RotateCw className={cn("h-3.5 w-3.5 text-muted-foreground", rotateToken.isPending && "animate-spin")} />+ </Button>+ )}{deleteButton}</div>)}@@ -632,6 +635,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {const [triggerDialogOpen, setTriggerDialogOpen] = useState(false);const [editDialogOpen, setEditDialogOpen] = useState(false);+ const [accessDialogOpen, setAccessDialogOpen] = useState(false);const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);const [deleting, setDeleting] = useState(false);@@ -683,6 +687,15 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {}const { autopilot, triggers } = data;+ const collaborators = data.collaborators ?? [];+ // Treat an absent can_write (older server) as "allowed" — the backend is the+ // real gate, so the UI only hides controls when the server explicitly says+ // the caller cannot write.+ const canWrite = autopilot.can_write !== false;+ // Managing the access list is narrower than write: granted collaborators can+ // edit/run but cannot grant/revoke. Fall back to canWrite when the server+ // doesn't send the field (older backend).+ const canManageAccess = autopilot.can_manage_access ?? canWrite;const handleRunNow = async () => {try {@@ -745,30 +758,38 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {</>}actions={- <>- <Button size="sm" variant="outline" onClick={() => setEditDialogOpen(true)} className="px-2 sm:px-2.5" aria-label={t(($) => $.detail.edit)}>- <Pencil className="h-3.5 w-3.5 sm:mr-1" />- <span className="hidden sm:inline">{t(($) => $.detail.edit)}</span>- </Button>- <Button- size="sm"- onClick={handleRunNow}- disabled={autopilot.status !== "active" || triggerAutopilot.isPending}- className="px-2 sm:px-2.5"- aria-label={triggerAutopilot.isPending ? t(($) => $.detail.running) : t(($) => $.detail.run_now)}- >- {triggerAutopilot.isPending ? (- <Loader2 className="h-3.5 w-3.5 sm:mr-1 animate-spin" />- ) : (- <Play className="h-3.5 w-3.5 sm:mr-1" />+ canWrite ? (+ <>+ {canManageAccess && (+ <Button size="sm" variant="outline" onClick={() => setAccessDialogOpen(true)} className="px-2 sm:px-2.5" aria-label={t(($) => $.detail.manage_access)}>+ <Users className="h-3.5 w-3.5 sm:mr-1" />+ <span className="hidden sm:inline">{t(($) => $.detail.manage_access)}</span>+ </Button>)}- <span className="hidden sm:inline">- {triggerAutopilot.isPending- ? t(($) => $.detail.running)- : t(($) => $.detail.run_now)}- </span>- </Button>- </>+ <Button size="sm" variant="outline" onClick={() => setEditDialogOpen(true)} className="px-2 sm:px-2.5" aria-label={t(($) => $.detail.edit)}>+ <Pencil className="h-3.5 w-3.5 sm:mr-1" />+ <span className="hidden sm:inline">{t(($) => $.detail.edit)}</span>+ </Button>+ <Button+ size="sm"+ onClick={handleRunNow}+ disabled={autopilot.status !== "active" || triggerAutopilot.isPending}+ className="px-2 sm:px-2.5"+ aria-label={triggerAutopilot.isPending ? t(($) => $.detail.running) : t(($) => $.detail.run_now)}+ >+ {triggerAutopilot.isPending ? (+ <Loader2 className="h-3.5 w-3.5 sm:mr-1 animate-spin" />+ ) : (+ <Play className="h-3.5 w-3.5 sm:mr-1" />+ )}+ <span className="hidden sm:inline">+ {triggerAutopilot.isPending+ ? t(($) => $.detail.running)+ : t(($) => $.detail.run_now)}+ </span>+ </Button>+ </>+ ) : null}/>@@ -868,10 +889,12 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {<h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">{t(($) => $.detail.section_triggers)}</h2>- <Button size="sm" variant="outline" onClick={() => setTriggerDialogOpen(true)}>- <Plus className="h-3.5 w-3.5 mr-1" />- {t(($) => $.detail.add_trigger)}- </Button>+ {canWrite && (+ <Button size="sm" variant="outline" onClick={() => setTriggerDialogOpen(true)}>+ <Plus className="h-3.5 w-3.5 mr-1" />+ {t(($) => $.detail.add_trigger)}+ </Button>+ )}</div>{triggers.length === 0 ? (<div className="rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">@@ -880,7 +903,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {) : (<div className="space-y-2">{triggers.map((trig) => (- <TriggerRow key={trig.id} trigger={trig} autopilotId={autopilotId} />+ <TriggerRow key={trig.id} trigger={trig} autopilotId={autopilotId} canWrite={canWrite} />))}</div>)}@@ -919,15 +942,17 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {</section>{/* Danger zone */}- <section className="space-y-3 pt-4 border-t">- <h2 className="text-sm font-medium text-destructive uppercase tracking-wider">- {t(($) => $.detail.section_danger)}- </h2>- <Button size="sm" variant="destructive" onClick={() => setDeleteConfirmOpen(true)}>- <Trash2 className="h-3.5 w-3.5 mr-1" />- {t(($) => $.detail.delete_button)}- </Button>- </section>+ {canWrite && (+ <section className="space-y-3 pt-4 border-t">+ <h2 className="text-sm font-medium text-destructive uppercase tracking-wider">+ {t(($) => $.detail.section_danger)}+ </h2>+ <Button size="sm" variant="destructive" onClick={() => setDeleteConfirmOpen(true)}>+ <Trash2 className="h-3.5 w-3.5 mr-1" />+ {t(($) => $.detail.delete_button)}+ </Button>+ </section>+ )}</div></div>@@ -957,6 +982,14 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {triggers={triggers}/>)}+ {accessDialogOpen && (+ <ManageAccessDialog+ open={accessDialogOpen}+ onOpenChange={setAccessDialogOpen}+ autopilotId={autopilot.id}+ collaborators={collaborators}+ />+ )}<AlertDialogopen={deleteConfirmOpen}onOpenChange={(v) => { if (!v && !deleting) setDeleteConfirmOpen(false); }}diff --git a/packages/views/autopilots/components/autopilot-list-actions.tsx b/packages/views/autopilots/components/autopilot-list-actions.tsxindex b28c7060ac..6285b4076c 100644--- a/packages/views/autopilots/components/autopilot-list-actions.tsx+++ b/packages/views/autopilots/components/autopilot-list-actions.tsx@@ -146,6 +146,11 @@ export function AutopilotRowActions({ row }: { row: Autopilot }) {const [deleteOpen, setDeleteOpen] = useState(false);const setStatus = useSetStatus();+ // The kebab only holds write actions (pause/resume/delete). Hide it entirely+ // for members without write access; an absent can_write (older server) keeps+ // the menu visible and lets the backend remain the gate.+ if (row.can_write === false) return null;+return (<spanonClick={(e) => e.stopPropagation()}diff --git a/packages/views/autopilots/components/manage-access-dialog.tsx b/packages/views/autopilots/components/manage-access-dialog.tsxnew file mode 100644index 0000000000..6fe5b173f6--- /dev/null+++ b/packages/views/autopilots/components/manage-access-dialog.tsx@@ -0,0 +1,177 @@+"use client";++import { useMemo, useState } from "react";+import { Plus, X } from "lucide-react";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { memberListOptions } from "@multica/core/workspace/queries";+import { useActorName } from "@multica/core/workspace/hooks";+import {+ useGrantAutopilotAccess,+ useRevokeAutopilotAccess,+} from "@multica/core/autopilots/mutations";+import type { AutopilotCollaborator } from "@multica/core/types";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { toast } from "sonner";+import { ActorAvatar } from "../../common/actor-avatar";+import {+ PropertyPicker,+ PickerItem,+ PickerEmpty,+} from "../../issues/components/pickers/property-picker";+import { matchesPinyin } from "../../editor/extensions/pinyin-match";+import { useT } from "../../i18n";++// Grant / revoke explicit write access to an autopilot. Members-only, mirroring+// the subscriber picker. Creators and workspace admins always have access and+// are not listed here — this manages the additional, explicitly-granted set.+export function ManageAccessDialog({+ open,+ onOpenChange,+ autopilotId,+ collaborators,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ autopilotId: string;+ collaborators: AutopilotCollaborator[];+}) {+ const { t } = useT("autopilots");+ const wsId = useWorkspaceId();+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const { getActorName } = useActorName();+ const grant = useGrantAutopilotAccess();+ const revoke = useRevokeAutopilotAccess();+ const [pickerOpen, setPickerOpen] = useState(false);+ const [filter, setFilter] = useState("");++ const grantedIds = useMemo(+ () => new Set(collaborators.map((c) => c.user_id)),+ [collaborators],+ );++ const query = filter.trim().toLowerCase();+ const candidates = useMemo(+ () =>+ members.filter(+ (m) =>+ !grantedIds.has(m.user_id) &&+ (query === "" ||+ m.name.toLowerCase().includes(query) ||+ matchesPinyin(m.name, query)),+ ),+ [members, grantedIds, query],+ );++ const handleGrant = async (userId: string) => {+ try {+ await grant.mutateAsync({ autopilotId, userId });+ toast.success(t(($) => $.access.toast_granted));+ } catch (e: any) {+ toast.error(e?.message || t(($) => $.access.toast_failed));+ }+ };++ const handleRevoke = async (userId: string) => {+ try {+ await revoke.mutateAsync({ autopilotId, userId });+ toast.success(t(($) => $.access.toast_revoked));+ } catch (e: any) {+ toast.error(e?.message || t(($) => $.access.toast_failed));+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogTitle>{t(($) => $.access.title)}</DialogTitle>+ <p className="text-sm text-muted-foreground">+ {t(($) => $.access.description)}+ </p>++ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">+ {t(($) => $.access.current_label)}+ </span>+ <PropertyPicker+ open={pickerOpen}+ onOpenChange={(v) => {+ setPickerOpen(v);+ if (!v) setFilter("");+ }}+ width="w-64"+ align="start"+ searchable+ searchPlaceholder={t(($) => $.access.search_placeholder)}+ onSearchChange={setFilter}+ trigger={+ <span className="inline-flex cursor-pointer items-center gap-1 rounded-md border border-dashed px-2 py-1 text-xs text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground">+ <Plus className="size-3" />+ {t(($) => $.access.add)}+ </span>+ }+ >+ {candidates.length === 0 ? (+ <PickerEmpty />+ ) : (+ candidates.map((m) => (+ <PickerItem+ key={m.user_id}+ selected={false}+ onClick={() => {+ void handleGrant(m.user_id);+ setPickerOpen(false);+ }}+ >+ <ActorAvatar actorType="member" actorId={m.user_id} size={18} />+ <span className="truncate">{m.name}</span>+ </PickerItem>+ ))+ )}+ </PropertyPicker>+ </div>++ {collaborators.length === 0 ? (+ <p className="rounded-md border border-dashed px-3 py-4 text-center text-sm text-muted-foreground">+ {t(($) => $.access.empty)}+ </p>+ ) : (+ <ul className="space-y-1">+ {collaborators.map((c) => (+ <li+ key={c.user_id}+ className="flex items-center justify-between rounded-md px-2 py-1.5 hover:bg-muted/50"+ >+ <span className="flex min-w-0 items-center gap-2">+ <ActorAvatar actorType="member" actorId={c.user_id} size={20} />+ <span className="truncate text-sm">+ {getActorName("member", c.user_id)}+ </span>+ </span>+ <button+ type="button"+ onClick={() => void handleRevoke(c.user_id)}+ disabled={revoke.isPending}+ className="cursor-pointer text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"+ aria-label={t(($) => $.access.remove_tooltip)}+ >+ <X className="size-3.5" />+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>++ <p className="text-xs text-muted-foreground">+ {t(($) => $.access.owner_note)}+ </p>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex 0da2164637..2af9aa8c0d 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -70,6 +70,7 @@"pause_aria": "Pause autopilot","activate_aria": "Activate autopilot","edit": "Edit",+ "manage_access": "Manage access","run_now": "Run now","running": "Running...","toast_triggered": "Autopilot triggered",@@ -101,6 +102,20 @@"deleting": "Deleting..."}},+ "access": {+ "title": "Manage access",+ "description": "Members you add can edit, run, and manage this autopilot's triggers and webhooks.",+ "current_label": "With access",+ "add": "Add member",+ "search_placeholder": "Search members…",+ "no_results": "No members found",+ "remove_tooltip": "Remove access",+ "empty": "No one has been granted access yet.",+ "toast_granted": "Access granted",+ "toast_revoked": "Access removed",+ "toast_failed": "Couldn't update access",+ "owner_note": "The creator and workspace admins always have access."+ },"run_status": {"issue_created": "Issue Created","running": "Running",diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 7f3142f534..d02144667e 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -70,6 +70,7 @@"pause_aria": "オートパイロットを一時停止","activate_aria": "オートパイロットを有効化","edit": "編集",+ "manage_access": "アクセス管理","run_now": "今すぐ実行","running": "実行中...","toast_triggered": "オートパイロットを実行しました",@@ -101,6 +102,20 @@"deleting": "削除中..."}},+ "access": {+ "title": "アクセス管理",+ "description": "追加したメンバーは、このオートパイロットの編集・実行や、トリガー・Webhook の管理ができます。",+ "current_label": "アクセス権あり",+ "add": "メンバーを追加",+ "search_placeholder": "メンバーを検索…",+ "no_results": "メンバーが見つかりません",+ "remove_tooltip": "アクセス権を削除",+ "empty": "まだ誰にもアクセス権が付与されていません。",+ "toast_granted": "アクセス権を付与しました",+ "toast_revoked": "アクセス権を削除しました",+ "toast_failed": "アクセス権を更新できませんでした",+ "owner_note": "作成者とワークスペース管理者は常にアクセスできます。"+ },"run_status": {"issue_created": "イシュー作成済み","running": "実行中",diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex bbcd746fa3..e002e3e99b 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -70,6 +70,7 @@"pause_aria": "오토파일럿 일시 중지","activate_aria": "오토파일럿 활성화","edit": "수정",+ "manage_access": "접근 권한 관리","run_now": "지금 실행","running": "실행 중...","toast_triggered": "오토파일럿을 실행했습니다",@@ -101,6 +102,20 @@"deleting": "삭제하는 중..."}},+ "access": {+ "title": "접근 권한 관리",+ "description": "추가한 멤버는 이 오토파일럿을 수정·실행하고 트리거와 webhook을 관리할 수 있습니다.",+ "current_label": "접근 가능",+ "add": "멤버 추가",+ "search_placeholder": "멤버 검색…",+ "no_results": "멤버를 찾을 수 없습니다",+ "remove_tooltip": "접근 권한 제거",+ "empty": "아직 아무에게도 접근 권한을 부여하지 않았습니다.",+ "toast_granted": "접근 권한을 부여했습니다",+ "toast_revoked": "접근 권한을 제거했습니다",+ "toast_failed": "접근 권한을 업데이트하지 못했습니다",+ "owner_note": "작성자와 워크스페이스 관리자는 항상 접근할 수 있습니다."+ },"run_status": {"issue_created": "이슈 생성됨","running": "실행 중",diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex 302c7a69b9..f3f6e70b46 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -70,6 +70,7 @@"pause_aria": "暂停自动化","activate_aria": "启用自动化","edit": "编辑",+ "manage_access": "管理访问","run_now": "立即运行","running": "运行中...","toast_triggered": "已触发自动化",@@ -101,6 +102,20 @@"deleting": "删除中..."}},+ "access": {+ "title": "管理访问",+ "description": "你添加的成员可以编辑、运行并管理这个自动化的触发器和 webhook。",+ "current_label": "已授权",+ "add": "添加成员",+ "search_placeholder": "搜索成员…",+ "no_results": "未找到成员",+ "remove_tooltip": "移除访问权限",+ "empty": "还没有授权任何人。",+ "toast_granted": "已授予访问权限",+ "toast_revoked": "已移除访问权限",+ "toast_failed": "更新访问权限失败",+ "owner_note": "创建者和工作区管理员始终拥有访问权限。"+ },"run_status": {"issue_created": "已创建 issue","running": "运行中",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e0d4d6710c..06d3161e3d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -960,6 +960,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/rotate-webhook-token", h.RotateAutopilotTriggerWebhookToken)r.Put("/signing-secret", h.SetAutopilotTriggerSigningSecret)})+ r.Post("/collaborators", h.AddAutopilotCollaborator)+ r.Delete("/collaborators/{userId}", h.RemoveAutopilotCollaborator)})})diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex e531501310..f75cef3d20 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -1,6 +1,7 @@package handlerimport (+ "context""encoding/json""fmt""io"@@ -56,6 +57,38 @@ type AutopilotResponse struct {// Always non-nil (empty slice when no subscribers configured) so// frontend optional-chain rules can treat the field as authoritative.Subscribers []AutopilotSubscriberEntry `json:"subscribers"`++ // CanWrite reports whether the requesting caller may perform write/execute+ // operations on this autopilot — editing, deleting, triggering, and+ // managing triggers/webhook secrets (creator, workspace owner/admin, or an+ // explicit collaborator). Nil on responses built without a caller in+ // context (older servers omit it; clients must treat absence as "unknown"+ // and fall back to attempting the action). See MUL-3807.+ CanWrite *bool `json:"can_write,omitempty"`++ // CanManageAccess reports whether the caller may manage the collaborator+ // (access) list — a narrower right held only by the creator and workspace+ // owners/admins, NOT by granted collaborators (who can write but cannot+ // re-grant). Nil when built without a caller in context. See MUL-3807.+ CanManageAccess *bool `json:"can_manage_access,omitempty"`+}++// AutopilotCollaboratorEntry is a member explicitly granted write access to an+// autopilot, surfaced on the detail response and the collaborator endpoints.+type AutopilotCollaboratorEntry struct {+ UserType string `json:"user_type"`+ UserID string `json:"user_id"`+ GrantedBy string `json:"granted_by"`+ CreatedAt string `json:"created_at"`+}++func collaboratorToEntry(c db.AutopilotCollaborator) AutopilotCollaboratorEntry {+ return AutopilotCollaboratorEntry{+ UserType: c.UserType,+ UserID: uuidToString(c.UserID),+ GrantedBy: uuidToString(c.GrantedBy),+ CreatedAt: timestampToString(c.CreatedAt),+ }}// user_type is restricted to "member" at the DB layer; the field is kept on@@ -361,6 +394,20 @@ func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {return}+ // Resolve the caller's write access for per-row can_write. The collaborator+ // grants are fetched once as a set (keyed by autopilot id) so the flag+ // costs no per-row query. A missing member (shouldn't happen behind the+ // workspace-member middleware) just yields can_write=false everywhere.+ caller, callerErr := h.getWorkspaceMember(r.Context(), requestUserID(r), workspaceID)+ collabSet := map[string]struct{}{}+ if callerErr == nil {+ if ids, err := h.Queries.ListAutopilotIDsForCollaborator(r.Context(), caller.UserID); err == nil {+ for _, id := range ids {+ collabSet[uuidToString(id)] = struct{}{}+ }+ }+ }+resp := make([]AutopilotResponse, len(autopilots))for i, row := range autopilots {// Omit subscribers to avoid an N+1; GET /api/autopilots/{id} is@@ -374,6 +421,11 @@ func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {s := row.LastRunStatusr.LastRunStatus = &s}+ if callerErr == nil {+ _, isCollaborator := collabSet[uuidToString(row.Autopilot.ID)]+ cw := autopilotWriteByOwnership(row.Autopilot, caller) || isCollaborator+ r.CanWrite = &cw+ }resp[i] = r}writeJSON(w, http.StatusOK, map[string]any{"autopilots": resp, "total": len(resp)})@@ -395,6 +447,24 @@ func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {}resp := autopilotToResponse(autopilot, subs)+ // Resolve the caller's write access once: it both stamps can_write and+ // gates webhook-secret exposure. Webhook tokens are trigger-granting+ // secrets (anyone who reads the token can fire the autopilot from outside+ // the permission system), so only writers — the creator, a workspace+ // owner/admin, or a granted collaborator — get the live token/URL; every+ // other member sees the trigger metadata with the secret fields stripped+ // (MUL-3807).+ canWrite := false+ canManageAccess := false+ if member, err := h.getWorkspaceMember(r.Context(), requestUserID(r), workspaceID); err == nil {+ canWrite = h.memberCanWriteAutopilot(r.Context(), autopilot, member)+ // Managing the access list is narrower than write: collaborators can+ // write but cannot re-grant (MUL-3807).+ canManageAccess = autopilotWriteByOwnership(autopilot, member)+ }+ resp.CanWrite = &canWrite+ resp.CanManageAccess = &canManageAccess+// Include triggers.triggers, err := h.Queries.ListAutopilotTriggers(r.Context(), autopilot.ID)if err != nil {@@ -402,12 +472,30 @@ func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {}triggerResp := make([]AutopilotTriggerResponse, len(triggers))for i, t := range triggers {- triggerResp[i] = h.triggerToResponse(t)+ tr := h.triggerToResponse(t)+ if !canWrite {+ tr.WebhookToken = nil+ tr.WebhookPath = nil+ tr.WebhookURL = nil+ }+ triggerResp[i] = tr+ }++ // Include the explicit collaborator grants so the "manage access" UI can+ // render the current list without a second round-trip.+ collaborators, err := h.Queries.ListAutopilotCollaborators(r.Context(), autopilot.ID)+ if err != nil {+ collaborators = nil+ }+ collabResp := make([]AutopilotCollaboratorEntry, len(collaborators))+ for i, c := range collaborators {+ collabResp[i] = collaboratorToEntry(c)}writeJSON(w, http.StatusOK, map[string]any{- "autopilot": resp,- "triggers": triggerResp,+ "autopilot": resp,+ "triggers": triggerResp,+ "collaborators": collabResp,})}@@ -432,6 +520,70 @@ func (h *Handler) loadAutopilotInWorkspace(w http.ResponseWriter, r *http.Requesreturn autopilot, true}+// autopilotWriteByOwnership is the implicit, query-free part of the write+// predicate: the autopilot's creator and workspace owners/admins always have+// write access. Explicit collaborator grants (memberCanWriteAutopilot) layer+// on top of this (MUL-3807).+func autopilotWriteByOwnership(ap db.Autopilot, member db.Member) bool {+ if roleAllowed(member.Role, "owner", "admin") {+ return true+ }+ return ap.CreatedByType == "member" && uuidToString(ap.CreatedByID) == uuidToString(member.UserID)+}++// memberCanWriteAutopilot reports whether the given member may perform write or+// execute operations on the autopilot — editing it, deleting it, triggering+// runs, replaying deliveries, and managing its triggers, webhook secrets, and+// access list. Write access is held by the autopilot's creator, by workspace+// owners/admins, and by members explicitly granted as collaborators. The same+// predicate also gates whether webhook secrets are exposed on the read path,+// since seeing a webhook token is equivalent to being able to trigger.+func (h *Handler) memberCanWriteAutopilot(ctx context.Context, ap db.Autopilot, member db.Member) bool {+ if autopilotWriteByOwnership(ap, member) {+ return true+ }+ granted, err := h.Queries.IsAutopilotCollaborator(ctx, db.IsAutopilotCollaboratorParams{+ AutopilotID: ap.ID,+ UserID: member.UserID,+ })+ return err == nil && granted+}++// requireAutopilotWrite enforces memberCanWriteAutopilot for a mutating/+// executing request. On failure it writes the response (404 when the caller is+// not a member of the workspace, 403 otherwise) and returns false; the caller+// must return early. On success it returns true.+func (h *Handler) requireAutopilotWrite(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) bool {+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return false+ }+ if !h.memberCanWriteAutopilot(r.Context(), ap, member) {+ writeError(w, http.StatusForbidden, "only the autopilot creator, a workspace admin, or a granted collaborator can manage this autopilot")+ return false+ }+ return true+}++// requireAutopilotAccessManagement enforces the narrower predicate used by the+// collaborator (access list) endpoints: only the autopilot's creator or a+// workspace owner/admin may grant or revoke access. A granted collaborator+// keeps its own write/execute rights (edit, trigger, manage triggers/secrets)+// but cannot manage the access list — this stops a collaborator from+// re-granting access to others or revoking peers (privilege escalation).+// See MUL-3807.+func (h *Handler) requireAutopilotAccessManagement(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) bool {+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return false+ }+ if !autopilotWriteByOwnership(ap, member) {+ writeError(w, http.StatusForbidden, "only the autopilot creator or a workspace admin can manage access")+ return false+ }+ return true+}+func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {var req CreateAutopilotRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -603,6 +755,9 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireAutopilotWrite(w, r, prev, workspaceID) {+ return+ }userID, ok := requireUserID(w, r)if !ok {@@ -799,13 +954,17 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {return}- if _, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ap, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{ID: idUUID,WorkspaceID: wsUUID,- }); err != nil {+ })+ if err != nil {writeError(w, http.StatusNotFound, "autopilot not found")return}+ if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ return+ }userID, ok := requireUserID(w, r)if !ok {@@ -828,6 +987,10 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete autopilot")return}+ if err := qtx.DeleteAutopilotCollaboratorsForAutopilot(r.Context(), idUUID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")+ return+ }if err := qtx.DeleteAutopilot(r.Context(), idUUID); err != nil {writeError(w, http.StatusInternalServerError, "failed to delete autopilot")return@@ -841,6 +1004,123 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusNoContent)}+// ── Collaborator (access grant) management ───────────────────────────────────++type AutopilotCollaboratorRequest struct {+ UserID string `json:"user_id"`+}++func (h *Handler) writeAutopilotCollaborators(w http.ResponseWriter, r *http.Request, autopilotID pgtype.UUID, status int) {+ collaborators, err := h.Queries.ListAutopilotCollaborators(r.Context(), autopilotID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load collaborators")+ return+ }+ resp := make([]AutopilotCollaboratorEntry, len(collaborators))+ for i, c := range collaborators {+ resp[i] = collaboratorToEntry(c)+ }+ writeJSON(w, status, map[string]any{"collaborators": resp})+}++// AddAutopilotCollaborator grants a workspace member explicit write access to+// the autopilot. Only the autopilot's creator or a workspace owner/admin can+// manage the access list; a granted collaborator cannot re-grant to others+// (privilege escalation). See MUL-3807.+func (h *Handler) AddAutopilotCollaborator(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ workspaceID := h.resolveWorkspaceID(r)++ ap, ok := h.loadAutopilotInWorkspace(w, r, id, workspaceID)+ if !ok {+ return+ }+ if !h.requireAutopilotAccessManagement(w, r, ap, workspaceID) {+ return+ }++ var req AutopilotCollaboratorRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.UserID == "" {+ writeError(w, http.StatusBadRequest, "user_id is required")+ return+ }+ targetUUID, ok := parseUUIDOrBadRequest(w, req.UserID, "user_id")+ if !ok {+ return+ }+ // Only workspace members can be granted access — agents already reach+ // autopilots through their own dispatch path, not this grant list.+ if !h.isWorkspaceEntity(r.Context(), "member", req.UserID, workspaceID) {+ writeError(w, http.StatusBadRequest, "user_id must be a member of this workspace")+ return+ }++ grantedBy, ok := requireUserID(w, r)+ if !ok {+ return+ }+ grantedByUUID, ok := parseUUIDOrBadRequest(w, grantedBy, "granted_by")+ if !ok {+ return+ }++ if _, err := h.Queries.AddAutopilotCollaborator(r.Context(), db.AddAutopilotCollaboratorParams{+ AutopilotID: ap.ID,+ UserType: "member",+ UserID: targetUUID,+ GrantedBy: grantedByUUID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to grant access")+ return+ }++ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", grantedBy, map[string]any{+ "autopilot_id": uuidToString(ap.ID),+ })+ h.writeAutopilotCollaborators(w, r, ap.ID, http.StatusCreated)+}++// RemoveAutopilotCollaborator revokes a member's explicit write grant. Only the+// autopilot's creator or a workspace owner/admin can manage the access list; a+// collaborator cannot revoke peers. Implicit writers (creator / owner / admin)+// are unaffected — there is no row to remove.+func (h *Handler) RemoveAutopilotCollaborator(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ userID := chi.URLParam(r, "userId")+ workspaceID := h.resolveWorkspaceID(r)++ ap, ok := h.loadAutopilotInWorkspace(w, r, id, workspaceID)+ if !ok {+ return+ }+ if !h.requireAutopilotAccessManagement(w, r, ap, workspaceID) {+ return+ }+ targetUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }++ if err := h.Queries.DeleteAutopilotCollaborator(r.Context(), db.DeleteAutopilotCollaboratorParams{+ AutopilotID: ap.ID,+ UserType: "member",+ UserID: targetUUID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to revoke access")+ return+ }++ actor := requestUserID(r)+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", actor, map[string]any{+ "autopilot_id": uuidToString(ap.ID),+ })+ h.writeAutopilotCollaborators(w, r, ap.ID, http.StatusOK)+}+// ── Trigger management ──────────────────────────────────────────────────────func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request) {@@ -851,6 +1131,9 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)if !ok {return}+ if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ return+ }var req CreateAutopilotTriggerRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -1117,6 +1400,9 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)if !ok {return}+ if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ return+ }triggerUUID, ok := parseUUIDOrBadRequest(w, triggerID, "trigger id")if !ok {@@ -1252,13 +1538,17 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)return}- if _, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{+ ap, err := h.Queries.GetAutopilotInWorkspace(r.Context(), db.GetAutopilotInWorkspaceParams{ID: autopilotUUID,WorkspaceID: wsUUID,- }); err != nil {+ })+ if err != nil {writeError(w, http.StatusNotFound, "autopilot not found")return}+ if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ return+ }trigger, err := h.Queries.GetAutopilotTrigger(r.Context(), triggerUUID)if err != nil || uuidToString(trigger.AutopilotID) != uuidToString(autopilotUUID) {@@ -1296,6 +1586,9 @@ func (h *Handler) RotateAutopilotTriggerWebhookToken(w http.ResponseWriter, r *hif !ok {return}+ if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ return+ }triggerUUID, ok := parseUUIDOrBadRequest(w, triggerID, "trigger id")if !ok {@@ -1362,6 +1655,9 @@ func (h *Handler) SetAutopilotTriggerSigningSecret(w http.ResponseWriter, r *httif !ok {return}+ if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ return+ }triggerUUID, ok := parseUUIDOrBadRequest(w, triggerID, "trigger id")if !ok {return@@ -1505,6 +1801,9 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireAutopilotWrite(w, r, autopilot, workspaceID) {+ return+ }if autopilot.Status != "active" {writeError(w, http.StatusBadRequest, "autopilot is not active")returndiff --git a/server/internal/handler/autopilot_permissions_test.go b/server/internal/handler/autopilot_permissions_test.gonew file mode 100644index 0000000000..9d02dfbb67--- /dev/null+++ b/server/internal/handler/autopilot_permissions_test.go@@ -0,0 +1,423 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// createPlainMember adds a fresh member-role user to the test workspace and+// returns its user id. Used to exercise the autopilot write gate from the+// perspective of a member who is neither the creator nor a workspace admin.+func createPlainMember(t *testing.T, email string) string {+ t.Helper()+ ctx := context.Background()++ var userID string+ if err := testPool.QueryRow(ctx,+ `INSERT INTO "user" (name, email) VALUES ('AP Perm Member', $1) RETURNING id`,+ email,+ ).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID)+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })++ if _, err := testPool.Exec(ctx,+ `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,+ testWorkspaceID, userID,+ ); err != nil {+ t.Fatalf("add member: %v", err)+ }+ return userID+}++// createAutopilotAs creates an autopilot via the API as the given user (empty+// userID = workspace owner) assigned to a fresh public agent, and returns its+// id. The caller-supplied title prefix keeps cleanup queries unambiguous.+func createAutopilotAs(t *testing.T, userID, title string) string {+ t.Helper()+ agentID := createHandlerTestAgent(t, title+"-agent", nil)++ body := map[string]any{+ "title": title,+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ }+ w := httptest.NewRecorder()+ path := "/api/autopilots?workspace_id=" + testWorkspaceID+ var r *http.Request+ if userID == "" {+ r = newRequest("POST", path, body)+ } else {+ r = newRequestAs(userID, "POST", path, body)+ }+ testHandler.CreateAutopilot(w, r)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var ap AutopilotResponse+ if err := json.NewDecoder(w.Body).Decode(&ap); err != nil {+ t.Fatalf("decode autopilot: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM autopilot_run WHERE autopilot_id = $1`, ap.ID)+ testPool.Exec(context.Background(), `DELETE FROM autopilot_trigger WHERE autopilot_id = $1`, ap.ID)+ testPool.Exec(context.Background(), `DELETE FROM autopilot_collaborator WHERE autopilot_id = $1`, ap.ID)+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)+ })+ return ap.ID+}++// grantAutopilotAccess grants the target member write access via the API as the+// given caller (empty caller = workspace owner), asserting the expected status.+func grantAutopilotAccess(t *testing.T, caller, apID, targetUserID string, wantStatus int) {+ t.Helper()+ w := httptest.NewRecorder()+ path := "/api/autopilots/" + apID + "/collaborators?workspace_id=" + testWorkspaceID+ body := map[string]any{"user_id": targetUserID}+ var r *http.Request+ if caller == "" {+ r = newRequest("POST", path, body)+ } else {+ r = newRequestAs(caller, "POST", path, body)+ }+ r = withURLParam(r, "id", apID)+ testHandler.AddAutopilotCollaborator(w, r)+ if w.Code != wantStatus {+ t.Fatalf("AddAutopilotCollaborator: expected %d, got %d: %s", wantStatus, w.Code, w.Body.String())+ }+}++// autopilotCanWrite fetches the detail as the given caller and returns the+// can_write flag the server stamped for them.+func autopilotCanWrite(t *testing.T, caller, apID string) bool {+ t.Helper()+ w := httptest.NewRecorder()+ path := "/api/autopilots/" + apID + "?workspace_id=" + testWorkspaceID+ var r *http.Request+ if caller == "" {+ r = newRequest("GET", path, nil)+ } else {+ r = newRequestAs(caller, "GET", path, nil)+ }+ r = withURLParam(r, "id", apID)+ testHandler.GetAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("GetAutopilot: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var got struct {+ Autopilot AutopilotResponse `json:"autopilot"`+ }+ if err := json.NewDecoder(w.Body).Decode(&got); err != nil {+ t.Fatalf("decode autopilot: %v", err)+ }+ if got.Autopilot.CanWrite == nil {+ t.Fatalf("expected can_write to be set on detail response")+ }+ return *got.Autopilot.CanWrite+}++// autopilotCanManageAccess fetches the detail as the given caller and returns+// the can_manage_access flag (narrower than can_write — collaborators lack it).+func autopilotCanManageAccess(t *testing.T, caller, apID string) bool {+ t.Helper()+ w := httptest.NewRecorder()+ path := "/api/autopilots/" + apID + "?workspace_id=" + testWorkspaceID+ var r *http.Request+ if caller == "" {+ r = newRequest("GET", path, nil)+ } else {+ r = newRequestAs(caller, "GET", path, nil)+ }+ r = withURLParam(r, "id", apID)+ testHandler.GetAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("GetAutopilot: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var got struct {+ Autopilot AutopilotResponse `json:"autopilot"`+ }+ if err := json.NewDecoder(w.Body).Decode(&got); err != nil {+ t.Fatalf("decode autopilot: %v", err)+ }+ if got.Autopilot.CanManageAccess == nil {+ t.Fatalf("expected can_manage_access to be set on detail response")+ }+ return *got.Autopilot.CanManageAccess+}++// TestAutopilotCollaborator_GrantedMemberCanWrite verifies the full delegation+// flow: a non-creator member is blocked, becomes a writer once granted, and is+// blocked again after the grant is revoked (MUL-3807).+func TestAutopilotCollaborator_GrantedMemberCanWrite(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ apID := createAutopilotAs(t, "", "ap-collab-grant")+ member := createPlainMember(t, "[email protected]")++ updateAs := func(caller string) int {+ w := httptest.NewRecorder()+ r := newRequestAs(caller, "PATCH", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, map[string]any{"title": "edited by " + caller})+ r = withURLParam(r, "id", apID)+ testHandler.UpdateAutopilot(w, r)+ return w.Code+ }++ // Before grant: blocked, and can_write=false.+ if code := updateAs(member); code != http.StatusForbidden {+ t.Fatalf("pre-grant update: expected 403, got %d", code)+ }+ if autopilotCanWrite(t, member, apID) {+ t.Fatalf("pre-grant: expected can_write=false for member")+ }++ // Grant.+ grantAutopilotAccess(t, "", apID, member, http.StatusCreated)++ // After grant: allowed, and can_write=true.+ if !autopilotCanWrite(t, member, apID) {+ t.Fatalf("post-grant: expected can_write=true for collaborator")+ }+ if code := updateAs(member); code != http.StatusOK {+ t.Fatalf("post-grant update: expected 200, got %d", code)+ }++ // Revoke.+ w := httptest.NewRecorder()+ r := newRequest("DELETE", "/api/autopilots/"+apID+"/collaborators/"+member+"?workspace_id="+testWorkspaceID, nil)+ r = withURLParams(r, "id", apID, "userId", member)+ testHandler.RemoveAutopilotCollaborator(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("RemoveAutopilotCollaborator: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ // After revoke: blocked again.+ if code := updateAs(member); code != http.StatusForbidden {+ t.Fatalf("post-revoke update: expected 403, got %d", code)+ }+}++// TestAutopilotCollaborator_NonWriterCannotGrant verifies a member without write+// access cannot manage the access list, and granting a non-member is rejected.+func TestAutopilotCollaborator_NonWriterCannotGrant(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ apID := createAutopilotAs(t, "", "ap-collab-guard")+ stranger := createPlainMember(t, "[email protected]")+ victim := createPlainMember(t, "[email protected]")++ // A non-writer cannot grant access to anyone.+ grantAutopilotAccess(t, stranger, apID, victim, http.StatusForbidden)++ // Owner granting a non-member (random UUID) is rejected as bad input.+ grantAutopilotAccess(t, "", apID, "00000000-0000-0000-0000-000000000000", http.StatusBadRequest)+}++// TestAutopilotCollaborator_CannotManageAccessList verifies the privilege-+// escalation boundary: a granted collaborator keeps write/execute access but+// CANNOT manage the access list — they cannot grant access to others or revoke+// peers. Only the creator / owner / admin may manage access (MUL-3807).+func TestAutopilotCollaborator_CannotManageAccessList(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ apID := createAutopilotAs(t, "", "ap-collab-noescalate")+ carol := createPlainMember(t, "[email protected]")+ dave := createPlainMember(t, "[email protected]")+ bob := createPlainMember(t, "[email protected]")++ // Owner grants two collaborators.+ grantAutopilotAccess(t, "", apID, carol, http.StatusCreated)+ grantAutopilotAccess(t, "", apID, dave, http.StatusCreated)++ // Collaborator carol keeps write access (can still edit the autopilot).+ w := httptest.NewRecorder()+ r := newRequestAs(carol, "PATCH", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, map[string]any{"title": "carol edit"})+ r = withURLParam(r, "id", apID)+ testHandler.UpdateAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("collaborator update: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ // ...but cannot grant access to a new member.+ grantAutopilotAccess(t, carol, apID, bob, http.StatusForbidden)++ // ...and cannot revoke a peer collaborator.+ w = httptest.NewRecorder()+ r = newRequestAs(carol, "DELETE", "/api/autopilots/"+apID+"/collaborators/"+dave+"?workspace_id="+testWorkspaceID, nil)+ r = withURLParams(r, "id", apID, "userId", dave)+ testHandler.RemoveAutopilotCollaborator(w, r)+ if w.Code != http.StatusForbidden {+ t.Fatalf("collaborator revoke peer: expected 403, got %d: %s", w.Code, w.Body.String())+ }++ // can_manage_access: false for the collaborator, true for the owner.+ if autopilotCanManageAccess(t, carol, apID) {+ t.Fatalf("carol can_manage_access: expected false")+ }+ if !autopilotCanManageAccess(t, "", apID) {+ t.Fatalf("owner can_manage_access: expected true")+ }+}++// TestAutopilotWrite_PlainMemberCannotMutateOthers verifies that a workspace+// member who is neither the creator nor an admin cannot edit, trigger, or+// delete an autopilot created by someone else (MUL-3807).+func TestAutopilotWrite_PlainMemberCannotMutateOthers(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ apID := createAutopilotAs(t, "", "ap-perm-owner-created")+ member := createPlainMember(t, "[email protected]")++ // Update.+ w := httptest.NewRecorder()+ r := newRequestAs(member, "PATCH", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, map[string]any{"title": "hijacked"})+ r = withURLParam(r, "id", apID)+ testHandler.UpdateAutopilot(w, r)+ if w.Code != http.StatusForbidden {+ t.Fatalf("UpdateAutopilot by stranger: expected 403, got %d: %s", w.Code, w.Body.String())+ }++ // Trigger.+ w = httptest.NewRecorder()+ r = newRequestAs(member, "POST", "/api/autopilots/"+apID+"/trigger?workspace_id="+testWorkspaceID, nil)+ r = withURLParam(r, "id", apID)+ testHandler.TriggerAutopilot(w, r)+ if w.Code != http.StatusForbidden {+ t.Fatalf("TriggerAutopilot by stranger: expected 403, got %d: %s", w.Code, w.Body.String())+ }++ // Delete.+ w = httptest.NewRecorder()+ r = newRequestAs(member, "DELETE", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, nil)+ r = withURLParam(r, "id", apID)+ testHandler.DeleteAutopilot(w, r)+ if w.Code != http.StatusForbidden {+ t.Fatalf("DeleteAutopilot by stranger: expected 403, got %d: %s", w.Code, w.Body.String())+ }+}++// TestAutopilotWrite_CreatorCanMutateOwn verifies that the member who created+// an autopilot retains write access to it even without an admin role.+func TestAutopilotWrite_CreatorCanMutateOwn(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ member := createPlainMember(t, "[email protected]")+ apID := createAutopilotAs(t, member, "ap-perm-member-created")++ w := httptest.NewRecorder()+ r := newRequestAs(member, "PATCH", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, map[string]any{"title": "creator edit"})+ r = withURLParam(r, "id", apID)+ testHandler.UpdateAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAutopilot by creator: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++// TestAutopilotWrite_AdminCanMutateMembersAutopilot verifies that a workspace+// owner/admin can manage an autopilot created by a plain member.+func TestAutopilotWrite_AdminCanMutateMembersAutopilot(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ member := createPlainMember(t, "[email protected]")+ apID := createAutopilotAs(t, member, "ap-perm-admin-target")++ // testUserID is the workspace owner.+ w := httptest.NewRecorder()+ r := newRequest("PATCH", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, map[string]any{"title": "admin edit"})+ r = withURLParam(r, "id", apID)+ testHandler.UpdateAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAutopilot by owner: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++// TestAutopilotWrite_WebhookSecretRedactedForNonWriter verifies that the+// webhook token/path are returned to a writer (the owner) but stripped from+// the read response for a member who lacks write access — seeing the token is+// equivalent to being able to trigger the autopilot (MUL-3807).+func TestAutopilotWrite_WebhookSecretRedactedForNonWriter(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ apID := createAutopilotAs(t, "", "ap-perm-secret")+ stranger := createPlainMember(t, "[email protected]")++ // Owner adds a webhook trigger.+ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/autopilots/"+apID+"/triggers?workspace_id="+testWorkspaceID, map[string]any{"kind": "webhook"})+ r = withURLParam(r, "id", apID)+ testHandler.CreateAutopilotTrigger(w, r)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateAutopilotTrigger: expected 201, got %d: %s", w.Code, w.Body.String())+ }++ type getResp struct {+ Triggers []AutopilotTriggerResponse `json:"triggers"`+ }++ // Owner (writer) sees the secret.+ w = httptest.NewRecorder()+ r = withURLParam(newRequest("GET", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, nil), "id", apID)+ testHandler.GetAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("GetAutopilot as owner: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var ownerView getResp+ if err := json.NewDecoder(w.Body).Decode(&ownerView); err != nil {+ t.Fatalf("decode owner view: %v", err)+ }+ if len(ownerView.Triggers) != 1 {+ t.Fatalf("owner view: expected 1 trigger, got %d", len(ownerView.Triggers))+ }+ if ownerView.Triggers[0].WebhookToken == nil || *ownerView.Triggers[0].WebhookToken == "" {+ t.Fatalf("owner view: expected webhook_token to be present")+ }+ if ownerView.Triggers[0].WebhookPath == nil {+ t.Fatalf("owner view: expected webhook_path to be present")+ }++ // Plain member (non-writer) sees the trigger but not the secret.+ w = httptest.NewRecorder()+ r = withURLParam(newRequestAs(stranger, "GET", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, nil), "id", apID)+ testHandler.GetAutopilot(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("GetAutopilot as stranger: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var strangerView getResp+ if err := json.NewDecoder(w.Body).Decode(&strangerView); err != nil {+ t.Fatalf("decode stranger view: %v", err)+ }+ if len(strangerView.Triggers) != 1 {+ t.Fatalf("stranger view: expected 1 trigger, got %d", len(strangerView.Triggers))+ }+ if strangerView.Triggers[0].Kind != "webhook" {+ t.Fatalf("stranger view: expected webhook trigger to remain visible, got kind %q", strangerView.Triggers[0].Kind)+ }+ if strangerView.Triggers[0].WebhookToken != nil {+ t.Fatalf("stranger view: webhook_token leaked: %v", *strangerView.Triggers[0].WebhookToken)+ }+ if strangerView.Triggers[0].WebhookPath != nil {+ t.Fatalf("stranger view: webhook_path leaked: %v", *strangerView.Triggers[0].WebhookPath)+ }+ if strangerView.Triggers[0].WebhookURL != nil {+ t.Fatalf("stranger view: webhook_url leaked: %v", *strangerView.Triggers[0].WebhookURL)+ }+}diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.goindex f6099f370b..9a78d8c20e 100644--- a/server/internal/handler/webhook_delivery.go+++ b/server/internal/handler/webhook_delivery.go@@ -227,6 +227,9 @@ func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Requestif !ok {return}+ if !h.requireAutopilotWrite(w, r, autopilot, workspaceID) {+ return+ }original, ok := h.loadDeliveryForAutopilot(w, r, autopilot, deliveryID)if !ok {returndiff --git a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.mdindex 038df105e1..d394eb0601 100644--- a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md+++ b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md@@ -7,3 +7,5 @@- `resolveAutopilotLeader` resolves squad-assigned autopilots to the squad leader.- `AgentReadiness` blocks archived/runtime-unready agents before enqueue.- `server/cmd/server/router.go` exposes authenticated `/api/autopilots` routes and unauthenticated webhook ingress `/api/webhooks/autopilots/{token}`.+- Write/execute authorization lives in `autopilotWriteByOwnership` / `memberCanWriteAutopilot` / `requireAutopilotWrite` (`server/internal/handler/autopilot.go`): editing, deleting, triggering, replaying deliveries, and managing triggers/webhook secrets require the autopilot's creator, a workspace owner/admin, or an explicit collaborator. Reads (list/get/runs/deliveries) stay open to any workspace member, but `GetAutopilot` redacts `webhook_token`/`webhook_path`/`webhook_url` for callers who lack write access, since the token alone can trigger the autopilot. Creating a new autopilot is still open to any member (they become its creator). This is the autopilot-level View/Write layer; it is independent of, and ANDed with, the private-assignee-agent gate enforced at dispatch time in `shouldSkipDispatch`.+- Explicit write grants ("collaborators") are stored in the `autopilot_collaborator` table (migration 128, members-only, no FK — deleted alongside the autopilot in the delete transaction). Endpoints: `POST /api/autopilots/{id}/collaborators` (body `{user_id}`) and `DELETE /api/autopilots/{id}/collaborators/{userId}`, both gated by the NARROWER `requireAutopilotAccessManagement` (creator or workspace owner/admin only — a granted collaborator keeps write/execute but cannot re-grant or revoke peers, preventing privilege escalation), both returning the updated `{collaborators}` list. `GetAutopilot` embeds the `collaborators` array and stamps two per-caller booleans: `can_write` (gates edit/run/trigger controls) and the narrower `can_manage_access` (gates the "Manage access" entry). The web/desktop "Manage access" UI lives in `packages/views/autopilots/components/manage-access-dialog.tsx`.diff --git a/server/migrations/128_autopilot_collaborator.down.sql b/server/migrations/128_autopilot_collaborator.down.sqlnew file mode 100644index 0000000000..4eaa71daf1--- /dev/null+++ b/server/migrations/128_autopilot_collaborator.down.sql@@ -0,0 +1,2 @@+DROP INDEX IF EXISTS idx_autopilot_collaborator_user;+DROP TABLE IF EXISTS autopilot_collaborator;diff --git a/server/migrations/128_autopilot_collaborator.up.sql b/server/migrations/128_autopilot_collaborator.up.sqlnew file mode 100644index 0000000000..7c31975972--- /dev/null+++ b/server/migrations/128_autopilot_collaborator.up.sql@@ -0,0 +1,23 @@+-- Explicit write grants for autopilots: lets an autopilot's creator (or a+-- workspace owner/admin) authorize specific workspace members to manage the+-- autopilot, beyond the implicit "creator ∪ owner/admin" set. A member listed+-- here is treated as a writer — they can edit, delete, trigger, replay+-- deliveries, and manage triggers/webhook secrets (MUL-3807).+--+-- No foreign keys or cascades — autopilot existence and workspace membership+-- are enforced in the application layer (the autopilot delete handler removes+-- these rows in the same transaction; membership is checked at the API+-- boundary), per the repo rule. Mirrors autopilot_subscriber.+CREATE TABLE autopilot_collaborator (+ autopilot_id UUID NOT NULL,+ user_type TEXT NOT NULL CHECK (user_type IN ('member')),+ user_id UUID NOT NULL,+ granted_by UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (autopilot_id, user_type, user_id)+);++-- Reverse-lookup index for "which autopilots can this member write?" — the PK+-- can't answer that since autopilot_id is its leading column.+CREATE INDEX idx_autopilot_collaborator_user+ ON autopilot_collaborator (user_type, user_id);diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex b41d1910a4..078c80ed9b 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -11,6 +11,41 @@ import ("github.com/jackc/pgx/v5/pgtype")+const addAutopilotCollaborator = `-- name: AddAutopilotCollaborator :one+INSERT INTO autopilot_collaborator (autopilot_id, user_type, user_id, granted_by)+VALUES ($1, $2, $3, $4)+ON CONFLICT (autopilot_id, user_type, user_id)+ DO UPDATE SET granted_by = EXCLUDED.granted_by+RETURNING autopilot_id, user_type, user_id, granted_by, created_at+`++type AddAutopilotCollaboratorParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ UserType string `json:"user_type"`+ UserID pgtype.UUID `json:"user_id"`+ GrantedBy pgtype.UUID `json:"granted_by"`+}++// Re-granting an existing collaborator is a no-op that refreshes granted_by,+// so the call is idempotent from the API boundary.+func (q *Queries) AddAutopilotCollaborator(ctx context.Context, arg AddAutopilotCollaboratorParams) (AutopilotCollaborator, error) {+ row := q.db.QueryRow(ctx, addAutopilotCollaborator,+ arg.AutopilotID,+ arg.UserType,+ arg.UserID,+ arg.GrantedBy,+ )+ var i AutopilotCollaborator+ err := row.Scan(+ &i.AutopilotID,+ &i.UserType,+ &i.UserID,+ &i.GrantedBy,+ &i.CreatedAt,+ )+ return i, err+}+const addAutopilotSubscriber = `-- name: AddAutopilotSubscriber :execINSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)VALUES ($1, $2, $3)@@ -304,6 +339,33 @@ func (q *Queries) DeleteAutopilot(ctx context.Context, id pgtype.UUID) error {return err}+const deleteAutopilotCollaborator = `-- name: DeleteAutopilotCollaborator :exec+DELETE FROM autopilot_collaborator+WHERE autopilot_id = $1 AND user_type = $2 AND user_id = $3+`++type DeleteAutopilotCollaboratorParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ UserType string `json:"user_type"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) DeleteAutopilotCollaborator(ctx context.Context, arg DeleteAutopilotCollaboratorParams) error {+ _, err := q.db.Exec(ctx, deleteAutopilotCollaborator, arg.AutopilotID, arg.UserType, arg.UserID)+ return err+}++const deleteAutopilotCollaboratorsForAutopilot = `-- name: DeleteAutopilotCollaboratorsForAutopilot :exec+DELETE FROM autopilot_collaborator+WHERE autopilot_id = $1+`++// Application-layer cleanup run inside the autopilot delete transaction.+func (q *Queries) DeleteAutopilotCollaboratorsForAutopilot(ctx context.Context, autopilotID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteAutopilotCollaboratorsForAutopilot, autopilotID)+ return err+}+const deleteAutopilotSubscribersForAutopilot = `-- name: DeleteAutopilotSubscribersForAutopilot :execDELETE FROM autopilot_subscriberWHERE autopilot_id = $1@@ -587,6 +649,88 @@ func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgtreturn i, err}+const isAutopilotCollaborator = `-- name: IsAutopilotCollaborator :one+SELECT EXISTS (+ SELECT 1 FROM autopilot_collaborator+ WHERE autopilot_id = $1 AND user_type = 'member' AND user_id = $2+) AS is_collaborator+`++type IsAutopilotCollaboratorParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) IsAutopilotCollaborator(ctx context.Context, arg IsAutopilotCollaboratorParams) (bool, error) {+ row := q.db.QueryRow(ctx, isAutopilotCollaborator, arg.AutopilotID, arg.UserID)+ var is_collaborator bool+ err := row.Scan(&is_collaborator)+ return is_collaborator, err+}++const listAutopilotCollaborators = `-- name: ListAutopilotCollaborators :many++SELECT autopilot_id, user_type, user_id, granted_by, created_at FROM autopilot_collaborator+WHERE autopilot_id = $1+ORDER BY created_at ASC, user_id ASC+`++// =====================+// Autopilot Collaborators+// =====================+// ORDER BY created_at keeps row rendering stable across refreshes.+func (q *Queries) ListAutopilotCollaborators(ctx context.Context, autopilotID pgtype.UUID) ([]AutopilotCollaborator, error) {+ rows, err := q.db.Query(ctx, listAutopilotCollaborators, autopilotID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AutopilotCollaborator{}+ for rows.Next() {+ var i AutopilotCollaborator+ if err := rows.Scan(+ &i.AutopilotID,+ &i.UserType,+ &i.UserID,+ &i.GrantedBy,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listAutopilotIDsForCollaborator = `-- name: ListAutopilotIDsForCollaborator :many+SELECT autopilot_id FROM autopilot_collaborator+WHERE user_type = 'member' AND user_id = $1+`++// Powers the per-row can_write flag on the list endpoint without an N+1.+func (q *Queries) ListAutopilotIDsForCollaborator(ctx context.Context, userID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listAutopilotIDsForCollaborator, userID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var autopilot_id pgtype.UUID+ if err := rows.Scan(&autopilot_id); err != nil {+ return nil, err+ }+ items = append(items, autopilot_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listAutopilotRuns = `-- name: ListAutopilotRuns :manySELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at FROM autopilot_runWHERE autopilot_id = $1diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 389a294dfa..ecd37d0cbb 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -140,6 +140,14 @@ type Autopilot struct {ProjectID pgtype.UUID `json:"project_id"`}+type AutopilotCollaborator struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ UserType string `json:"user_type"`+ UserID pgtype.UUID `json:"user_id"`+ GrantedBy pgtype.UUID `json:"granted_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type AutopilotRun struct {ID pgtype.UUID `json:"id"`AutopilotID pgtype.UUID `json:"autopilot_id"`diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex d7c7e2ed1b..347cd9258f 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -413,3 +413,42 @@ ON CONFLICT (autopilot_id, user_type, user_id) DO NOTHING;DELETE FROM autopilot_subscriberWHERE autopilot_id = $1;+-- =====================+-- Autopilot Collaborators+-- =====================++-- name: ListAutopilotCollaborators :many+-- ORDER BY created_at keeps row rendering stable across refreshes.+SELECT * FROM autopilot_collaborator+WHERE autopilot_id = $1+ORDER BY created_at ASC, user_id ASC;++-- name: AddAutopilotCollaborator :one+-- Re-granting an existing collaborator is a no-op that refreshes granted_by,+-- so the call is idempotent from the API boundary.+INSERT INTO autopilot_collaborator (autopilot_id, user_type, user_id, granted_by)+VALUES ($1, $2, $3, $4)+ON CONFLICT (autopilot_id, user_type, user_id)+ DO UPDATE SET granted_by = EXCLUDED.granted_by+RETURNING *;++-- name: DeleteAutopilotCollaborator :exec+DELETE FROM autopilot_collaborator+WHERE autopilot_id = $1 AND user_type = $2 AND user_id = $3;++-- name: DeleteAutopilotCollaboratorsForAutopilot :exec+-- Application-layer cleanup run inside the autopilot delete transaction.+DELETE FROM autopilot_collaborator+WHERE autopilot_id = $1;++-- name: IsAutopilotCollaborator :one+SELECT EXISTS (+ SELECT 1 FROM autopilot_collaborator+ WHERE autopilot_id = $1 AND user_type = 'member' AND user_id = $2+) AS is_collaborator;++-- name: ListAutopilotIDsForCollaborator :many+-- Powers the per-row can_write flag on the list endpoint without an N+1.+SELECT autopilot_id FROM autopilot_collaborator+WHERE user_type = 'member' AND user_id = $1;+