Skip to content

Commit 985b399

Browse files
committed
feat(invites): support unlimited invite code usage
1 parent 0c47eaf commit 985b399

10 files changed

Lines changed: 311 additions & 18 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ GET /api/v1/domains/{domain}/activity — 日粒度创建、更新和成功
4747
GET /api/v1/domains — 领域清单(concept 数及聚合 created_at/updated_at)
4848
PUT /api/v1/domains/{domain} — 创建/更新 README、schema、visibility
4949
DELETE /api/v1/domains/{domain} — 级联删除 domain 全部数据
50+
POST /api/v1/domains/{domain}/invites — 生成邀请码(max_uses 0 = 不限次数,1-100 为次数上限)
5051
GET /api/v1/health — 健康检查
5152
```
5253

@@ -75,6 +76,7 @@ okp export <domain> — 导出 OKF bundle 文件树到本地
7576
okp lint <file> — 本地校验
7677
okp domains — 领域清单
7778
okp delete <id> — 删除 concept
79+
okp invite create <domain> [--max-uses 1 | --unlimited]
7880
okp skills install — 安装/更新 agent skills 到 {dir}/.agents/skills/(默认当前目录,幂等)
7981
okp skills list — 列出内置 skills 及版本
8082
```

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,14 @@ okp batch concepts.ndjson
100100
```bash
101101
okp invite create my-domain
102102
okp invite create my-private-domain --role reader
103+
okp invite create my-domain --max-uses 5
104+
okp invite create my-domain --unlimited
103105
okp invite accept OKP-XXXX-XXXX
104106
okp invite members my-domain
105107
```
106108

109+
`--max-uses` accepts 1-100 and defaults to 1. `--unlimited` issues a code that any number of people can accept until it expires or is revoked.
110+
107111
### Delete knowledge
108112

109113
```bash

‎cmd/cli/commands.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -559,17 +559,22 @@ func cmdInvite() *cobra.Command {
559559

560560
// okp invite create <domain>
561561
var expiresHours, maxUses int
562+
var unlimited bool
562563
var role string
563564
createCmd := &cobra.Command{
564565
Use: "create <domain>",
565566
Short: "创建 reader/writer 邀请码",
566567
Args: cobra.ExactArgs(1),
567568
RunE: func(cmd *cobra.Command, args []string) error {
568569
domain := args[0]
570+
uses := maxUses
571+
if unlimited {
572+
uses = 0 // 0 tells the API the code has no use limit
573+
}
569574
body := map[string]any{
570575
"role": role,
571576
"expires_in_hours": expiresHours,
572-
"max_uses": maxUses,
577+
"max_uses": uses,
573578
}
574579
resp, err := doRequest("POST", "/api/v1/domains/"+url.PathEscape(domain)+"/invites", body)
575580
if err != nil {
@@ -593,7 +598,9 @@ func cmdInvite() *cobra.Command {
593598
}
594599
createCmd.Flags().StringVar(&role, "role", "writer", "邀请角色: writer;private domain 也可用 reader")
595600
createCmd.Flags().IntVar(&expiresHours, "expires-hours", 72, "过期小时数")
596-
createCmd.Flags().IntVar(&maxUses, "max-uses", 1, "最大使用次数")
601+
createCmd.Flags().IntVar(&maxUses, "max-uses", 1, "最大使用次数(1-100)")
602+
createCmd.Flags().BoolVar(&unlimited, "unlimited", false, "不限使用次数(与 --max-uses 互斥)")
603+
createCmd.MarkFlagsMutuallyExclusive("max-uses", "unlimited")
597604
cmd.AddCommand(createCmd)
598605

599606
// okp invite list <domain>

‎cmd/cli/invite_test.go‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
)
9+
10+
// TestCmdInviteCreateUnlimitedSendsZero pins the CLI → API contract: the
11+
// unlimited flag must reach the API as max_uses=0, which the backend reads as
12+
// "no limit".
13+
func TestCmdInviteCreateUnlimitedSendsZero(t *testing.T) {
14+
var received map[string]any
15+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16+
if r.URL.Path != "/api/v1/domains/team/invites" {
17+
http.NotFound(w, r)
18+
return
19+
}
20+
if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
21+
t.Errorf("decode body: %v", err)
22+
}
23+
writeInviteResponse(t, w)
24+
}))
25+
defer srv.Close()
26+
27+
apiBase = srv.URL
28+
apiToken = ""
29+
defer func() { apiBase = "" }()
30+
31+
cmd := cmdInvite()
32+
cmd.SetArgs([]string{"create", "team", "--unlimited"})
33+
if err := cmd.Execute(); err != nil {
34+
t.Fatalf("invite create: %v", err)
35+
}
36+
37+
if got, ok := received["max_uses"].(float64); !ok || got != 0 {
38+
t.Fatalf("max_uses sent = %v, want 0 for unlimited", received["max_uses"])
39+
}
40+
}
41+
42+
// TestCmdInviteCreateMaxUsesStillSendsCount guards the bounded path.
43+
func TestCmdInviteCreateMaxUsesStillSendsCount(t *testing.T) {
44+
var received map[string]any
45+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
46+
if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
47+
t.Errorf("decode body: %v", err)
48+
}
49+
writeInviteResponse(t, w)
50+
}))
51+
defer srv.Close()
52+
53+
apiBase = srv.URL
54+
apiToken = ""
55+
defer func() { apiBase = "" }()
56+
57+
cmd := cmdInvite()
58+
cmd.SetArgs([]string{"create", "team", "--max-uses", "5"})
59+
if err := cmd.Execute(); err != nil {
60+
t.Fatalf("invite create: %v", err)
61+
}
62+
63+
if got, ok := received["max_uses"].(float64); !ok || got != 5 {
64+
t.Fatalf("max_uses sent = %v, want 5", received["max_uses"])
65+
}
66+
}
67+
68+
func TestCmdInviteCreateRejectsBothLimits(t *testing.T) {
69+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
70+
writeInviteResponse(t, w)
71+
}))
72+
defer srv.Close()
73+
74+
apiBase = srv.URL
75+
apiToken = ""
76+
defer func() { apiBase = "" }()
77+
78+
cmd := cmdInvite()
79+
cmd.SetArgs([]string{"create", "team", "--unlimited", "--max-uses", "3"})
80+
if err := cmd.Execute(); err == nil {
81+
t.Fatal("expected mutually exclusive flags to fail")
82+
}
83+
}
84+
85+
func writeInviteResponse(t *testing.T, w http.ResponseWriter) {
86+
t.Helper()
87+
w.Header().Set("Content-Type", "application/json")
88+
if err := json.NewEncoder(w).Encode(map[string]any{
89+
"id": "invite-1", "domain": "team", "role": "writer", "code": "OKP-TEST-CODE",
90+
"max_uses": 0, "used_count": 0, "unlimited": true,
91+
}); err != nil {
92+
t.Errorf("encode response: %v", err)
93+
}
94+
}

‎frontend/src/api/client.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ export interface CreateInviteResponse {
8686
created_at: string;
8787
expires_at: string;
8888
max_uses: number;
89+
unlimited?: boolean;
8990
used_count: number;
9091
code: string;
9192
work_url: string;
@@ -107,6 +108,7 @@ export interface DomainInviteRow {
107108
created_at: string;
108109
expires_at: string;
109110
max_uses: number;
111+
unlimited?: boolean;
110112
used_count: number;
111113
revoked_at?: string | null;
112114
last_used_at?: string | null;
@@ -240,6 +242,7 @@ export function useApi() {
240242
body: JSON.stringify({
241243
role: body?.role ?? "writer",
242244
expires_in_hours: body?.expires_in_hours ?? 72,
245+
// 0 means unlimited on the API side.
243246
max_uses: body?.max_uses ?? 1,
244247
}),
245248
},

‎frontend/src/routes/domain.$domain.tsx‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ function DomainPage() {
5858
const [createdInvite, setCreatedInvite] = useState<CreateInviteResponse | null>(null)
5959
const [inviteError, setInviteError] = useState<string | null>(null)
6060
const [inviteRole, setInviteRole] = useState<'reader' | 'writer'>('writer')
61+
// 0 means the invite code has no use limit.
62+
const [inviteMaxUses, setInviteMaxUses] = useState<number>(1)
6163

6264
const { data: concepts, isLoading } = useQuery({
6365
queryKey: ['domain', domain, offset],
@@ -114,7 +116,7 @@ function DomainPage() {
114116
})
115117

116118
const createInviteMutation = useMutation({
117-
mutationFn: () => api.createInvite(domain, { role: inviteRole, expires_in_hours: 72, max_uses: 1 }),
119+
mutationFn: () => api.createInvite(domain, { role: inviteRole, expires_in_hours: 72, max_uses: inviteMaxUses }),
118120
onSuccess: (res) => {
119121
setCreatedInvite(res)
120122
setInviteError(null)
@@ -260,7 +262,7 @@ function DomainPage() {
260262
<div>
261263
<Text weight="medium">邀请成员</Text>
262264
<Text size="sm" color="secondary">
263-
默认 72 小时、一次有效。
265+
默认 72 小时有效。
264266
</Text>
265267
</div>
266268
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
@@ -276,6 +278,20 @@ function DomainPage() {
276278
>可写</Button>
277279
</div>
278280
)}
281+
<div style={{ display: 'flex', gap: 6 }}>
282+
<Button
283+
variant={inviteMaxUses === 1 ? undefined : 'outline'}
284+
onClick={() => { setInviteMaxUses(1); setCreatedInvite(null) }}
285+
>1 次</Button>
286+
<Button
287+
variant={inviteMaxUses === 5 ? undefined : 'outline'}
288+
onClick={() => { setInviteMaxUses(5); setCreatedInvite(null) }}
289+
>5 次</Button>
290+
<Button
291+
variant={inviteMaxUses === 0 ? undefined : 'outline'}
292+
onClick={() => { setInviteMaxUses(0); setCreatedInvite(null) }}
293+
>不限次数</Button>
294+
</div>
279295
<Button
280296
onClick={() => createInviteMutation.mutate()}
281297
disabled={createInviteMutation.isPending}
@@ -299,7 +315,9 @@ function DomainPage() {
299315
flexDirection: 'column',
300316
gap: 8,
301317
}}>
302-
<Text size="sm" color="secondary">邀请码(只显示一次)</Text>
318+
<Text size="sm" color="secondary">
319+
邀请码(只显示一次,{createdInvite.max_uses > 0 ? `最多 ${createdInvite.max_uses} 次` : '不限次数'})
320+
</Text>
303321
<Text weight="medium" style={{ fontFamily: 'ui-monospace, monospace', fontSize: 18 }}>
304322
{createdInvite.code}
305323
</Text>
@@ -339,7 +357,7 @@ function DomainPage() {
339357
fontSize: 13,
340358
}}>
341359
<Text size="sm">
342-
{inv.role} · {inv.status} · {inv.used_count}/{inv.max_uses}
360+
{inv.role} · {inv.status} · {inv.used_count}/{inv.unlimited ? '∞' : inv.max_uses}
343361
</Text>
344362
{inv.status === 'active' && (
345363
<Button

0 commit comments

Comments
 (0)