diff --git a/nexus-platform/internal/ai/list_roles_test.go b/nexus-platform/internal/ai/list_roles_test.go index e2402cc..35e076a 100644 --- a/nexus-platform/internal/ai/list_roles_test.go +++ b/nexus-platform/internal/ai/list_roles_test.go @@ -10,8 +10,11 @@ package ai import ( "context" "encoding/json" + "slices" "strings" "testing" + + "nexus/platform/internal/services" ) func TestListRoles(t *testing.T) { @@ -54,3 +57,53 @@ func TestListRoles_EmptyTenantReturnsAnEmptyList(t *testing.T) { t.Errorf("out = %s, want an explicit empty array", out) } } + +// Issue #23: list_roles {grants: true} answers "who can edit contacts?" whole — every role of THIS +// tenant with its current grants, and nothing buffered (a read, so MCP may offer it too). +func TestListRoles_WithGrants(t *testing.T) { + e := accessExecutor(nil) + out := e.execute(context.Background(), "list_roles", `{"grants":true}`) + var got struct { + OK bool `json:"ok"` + Result struct { + Roles []struct { + Name string `json:"name"` + Label string `json:"label"` + Grants []services.RoleActionView `json:"grants"` + } `json:"roles"` + } `json:"result"` + } + if err := json.Unmarshal([]byte(out), &got); err != nil || !got.OK { + t.Fatalf("out = %s (%v); want ok", out, err) + } + byName := map[string][]services.RoleActionView{} + for _, r := range got.Result.Roles { + byName[r.Name] = r.Grants + } + if len(got.Result.Roles) != 5 || got.Result.Roles[0].Label != "Nhân viên kinh doanh" { + t.Fatalf("roles = %+v; want tenant A's five roles with their labels", got.Result.Roles) + } + rep := []services.RoleActionView{{EntityName: "crm_accounts", Action: "view", AccessLevel: "all"}, {EntityName: "crm_accounts", Action: "create", AccessLevel: "all"}, {EntityName: "crm_accounts", Action: "edit", AccessLevel: "owner"}} + if !slices.Equal(byName["crm_sales_rep"], rep) || !slices.Equal(byName["viewer"], []services.RoleActionView{{EntityName: "*", Action: "view", AccessLevel: "all"}}) { + t.Fatalf("grants = %+v; want the rep's three crm_accounts grants and viewer's \"*\" view", byName) + } + if g, ok := byName["ops"]; !ok || g == nil || len(g) != 0 { + t.Errorf("a role with no grant = %v; want an explicit empty list", g) + } + if strings.Contains(out, "b_only") { + t.Fatalf("another tenant's role leaked: %s", out) + } + if len(e.draft) != 0 { + t.Fatalf("draft = %+v; a read buffers nothing", e.draft) + } +} + +func TestListRoles_GrantsNeedTheRoleReader(t *testing.T) { + e := &toolExecutor{reader: twoTenantReader(), tenantID: "t1"} + if out := e.execute(context.Background(), "list_roles", `{"grants":true}`); !strings.Contains(out, "ROLES_GRANTS_UNAVAILABLE") { + t.Fatalf("out = %s; want ROLES_GRANTS_UNAVAILABLE", out) + } + if out := e.execute(context.Background(), "list_roles", `{"grants":"yes"}`); !strings.Contains(out, "INVALID_ARGS") { + t.Fatalf("out = %s; want INVALID_ARGS", out) + } +} diff --git a/nexus-platform/internal/ai/tools.go b/nexus-platform/internal/ai/tools.go index 11e8828..e86ab3f 100644 --- a/nexus-platform/internal/ai/tools.go +++ b/nexus-platform/internal/ai/tools.go @@ -538,10 +538,12 @@ func toolDefinitionsBase() []Tool { Type: "function", Function: ToolFunction{ Name: "list_roles", - Description: "Liệt kê TÊN các vai (role) đang có của tenant. BẮT BUỘC gọi trước khi dùng roleName trong propose_workqueue, người duyệt (approverType='role') trong propose_approval hoặc role trong propose_access — tên vai không có thật sẽ làm bước Apply thất bại. Chưa có vai phù hợp thì bỏ trống roleName (queue hiện với mọi người) hoặc dùng approverType='user'.", + Description: "Liệt kê TÊN các vai (role) đang có của tenant. BẮT BUỘC gọi trước khi dùng roleName trong propose_workqueue, người duyệt (approverType='role') trong propose_approval hoặc role trong propose_access — tên vai không có thật sẽ làm bước Apply thất bại. Chưa có vai phù hợp thì bỏ trống roleName (queue hiện với mọi người) hoặc dùng approverType='user'. grants: true → kèm quyền hiện có của từng vai (entityName '*' = mọi bảng, accessLevel = những bản ghi nào) để trả lời 'ai được xem / sửa bảng X'; quản trị viên bỏ qua quyền. Chỉ đọc, không ghi, không vào draft.", Parameters: map[string]any{ - "type": "object", - "properties": map[string]any{}, + "type": "object", + "properties": map[string]any{ + "grants": map[string]any{"type": "boolean", "description": "true: kèm quyền hiện có của từng vai."}, + }, }, }, }, @@ -803,7 +805,7 @@ func (e *toolExecutor) dispatch(ctx context.Context, name, argsJSON string) stri case "get_app": return e.getApp(ctx, argsJSON) case "list_roles": - return e.listRoles(ctx) + return e.listRoles(ctx, argsJSON) case "snapshot_model": return e.snapshotModel(ctx) case "propose_entity": @@ -1313,13 +1315,25 @@ func (p proposedField) toDraftField(entity string) DraftField { func ptrDraftField(f DraftField) *DraftField { return &f } -// listRoles returns the tenant's role names so the model can only NAME a role that exists. +// listRoles returns the tenant's role names so the model can only NAME a role that exists; with +// {grants: true}, every role with its grants (listRoleGrants, issue #23). // // propose_workqueue's roleName and propose_approval's role approver are resolved to ids at Apply, // and until now the model had no way to see the list — so it produced a reasonable-sounding name // and the Apply failed on a role nobody had created. Failing at Apply is the worst place to learn // it: the proposal already looked right and the person already pressed the button. -func (e *toolExecutor) listRoles(ctx context.Context) string { +func (e *toolExecutor) listRoles(ctx context.Context, argsJSON string) string { + var a struct { + Grants bool `json:"grants"` + } + if strings.TrimSpace(argsJSON) != "" { + if err := json.Unmarshal([]byte(argsJSON), &a); err != nil { + return toolErr("INVALID_ARGS: %v", err) + } + } + if a.Grants { + return e.listRoleGrants(ctx) + } names, err := e.reader.ListRoleNames(ctx, e.tenantID) if err != nil { return toolErr("ROLES_READ_FAILED: không đọc được danh sách vai: %v", err) @@ -3104,8 +3118,9 @@ func (e *toolExecutor) proposeWorkQueue(ctx context.Context, argsJSON string) st type accessUserLookup interface { GetUserByEmail(ctx context.Context, tenantID, email string) (*auth.User, error) GetUserByID(ctx context.Context, tenantID, id string) (*auth.User, error) - // ListUsers backs propose_access: never a role an admin or a platform operator holds. - ListUsers(ctx context.Context, tenantID string) ([]auth.User, error) + // PrivilegedHolders backs propose_access: the admins and platform operators holding one of + // roleIDs (never a role one of them holds), not every user of the tenant (issue #23). + PrivilegedHolders(ctx context.Context, tenantID string, roleIDs []string) ([]auth.User, error) } type accessRoleLookup interface { diff --git a/nexus-platform/internal/ai/tools_access.go b/nexus-platform/internal/ai/tools_access.go index 40cf786..6bb3374 100644 --- a/nexus-platform/internal/ai/tools_access.go +++ b/nexus-platform/internal/ai/tools_access.go @@ -103,7 +103,19 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin if err != nil { return toolErr("ACCESS_PROPOSE_FAILED: %v", err) } - users, err := probes.Users.ListUsers(ctx, e.tenantID) + // One query for the admins and operators holding a role this call names (issue #23): a refused + // grant is still judged in order below, so a role that does not resolve is simply not asked about. + var named []string + for _, g := range raw { + var ref string + if json.Unmarshal(g["role"], &ref) != nil { + continue // not a string: refused as INVALID_ARGS below + } + if r, msg := resolveAccessRole(roles, ref, 0); msg == "" { + named = append(named, r.ID) + } + } + users, err := probes.Users.PrivilegedHolders(ctx, e.tenantID, named) if err != nil { return toolErr("ACCESS_PROPOSE_FAILED: %v", err) } @@ -185,10 +197,7 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin e.draft = e.draft[:from] return toolErr("ACCESS_PROPOSE_FAILED: %v", err) } - before := make([]services.RoleActionView, len(acts)) - for i, a := range acts { - before[i] = services.RoleActionView{EntityName: a.EntityName, Action: a.Action, AccessLevel: a.AccessLevel} - } + before := grantViews(acts) after := mergeAccessGrants(before, p.grants) if slices.Equal(after, before) { unchanged = append(unchanged, p.role.Name) @@ -215,6 +224,43 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin return toolOK(out) } +// listRoleGrants is list_roles {grants: true} (issue #23): every role of the tenant with its current +// grants, so "who can edit contacts?" gets a whole answer. A read: the tenant is the executor's, +// nothing is buffered or written, which is why MCP offers it too. +// ponytail: two reads per role (ListActionsForRole re-checks the role's tenant); a tenant has tens of +// roles. One JOIN over acl_roles/acl_role_actions if that ever shows up. +func (e *toolExecutor) listRoleGrants(ctx context.Context) string { + var probes *AccessProbes + if c, ok := e.reader.(AccessProbeCarrier); ok { + probes = c.AccessProbes() + } + if probes == nil || probes.Roles == nil { + return toolErr("ROLES_GRANTS_UNAVAILABLE: server chưa nối bộ đọc vai cho AI Builder — gọi list_roles không kèm grants") + } + roles, err := probes.Roles.ListRoles(ctx, e.tenantID) + if err != nil { + return toolErr("ROLES_READ_FAILED: %v", err) + } + out := make([]map[string]any, 0, len(roles)) + for _, r := range roles { + acts, err := probes.Roles.ListActionsForRole(ctx, e.tenantID, r.ID) + if err != nil { + return toolErr("ROLES_READ_FAILED: role %q: %v", r.Name, err) + } + out = append(out, map[string]any{"name": r.Name, "label": r.Label, "grants": grantViews(acts)}) + } + return toolOK(map[string]any{"roles": out}) +} + +// grantViews is a role's grant rows as the API and the access card show them; never nil. +func grantViews(acts []auth.RoleAction) []services.RoleActionView { + out := make([]services.RoleActionView, len(acts)) + for i, a := range acts { + out[i] = services.RoleActionView{EntityName: a.EntityName, Action: a.Action, AccessLevel: a.AccessLevel} + } + return out +} + // resolveAccessRole finds the role by its name, else by its label when exactly one role carries it // (the builder may say "Nhân viên kinh doanh"). roles is tenant-pinned, so another tenant's role is // simply not there. The second value is the tool error ("" = found). @@ -239,7 +285,8 @@ func resolveAccessRole(roles []auth.Role, ref string, n int) (auth.Role, string) } // privilegedHolder says who makes the role privileged ("" = nobody): an admin or a platform operator -// holding it. They bypass access control anyway, and the assistant stays off their roles. +// holding it (users = PrivilegedHolders). They bypass access control anyway, and the assistant stays +// off their roles. func privilegedHolder(users []auth.User, roleID string) string { for _, u := range users { if u.RoleID == nil || *u.RoleID != roleID { diff --git a/nexus-platform/internal/ai/tools_access_test.go b/nexus-platform/internal/ai/tools_access_test.go index 1b66e9a..2f2b54f 100644 --- a/nexus-platform/internal/ai/tools_access_test.go +++ b/nexus-platform/internal/ai/tools_access_test.go @@ -152,6 +152,23 @@ func TestProposeAccess_BuffersOneCardPerRoleWithTheRoleChange(t *testing.T) { } } +// Issue #23: the admin check asks for the holders of the roles this call names, in this tenant, once +// — not for every user of the tenant. +func TestProposeAccess_AsksOnlyAboutTheNamedRoles(t *testing.T) { + e := withTickets(t, accessExecutor(fakeCutoff{at: &accCutoff})) + users := e.reader.(AccessProbeCarrier).AccessProbes().Users.(*fakeAccessUsers) + mustBuffer(t, e, "propose_access", grantArgs(grant("crm_sales_rep", "tickets", "all", "view"), grant("Xem tất cả", "tickets", "owner", "edit"))) + if len(users.asked) != 1 || !slices.Equal(users.asked[0], []string{"r-rep", "r-star"}) { + t.Fatalf("PrivilegedHolders asked %v; want one call for [r-rep r-star]", users.asked) + } + // A role that does not resolve is not asked about; the call is still refused for it, in order. + users.asked = nil + mustReject(t, e, "propose_access", grantArgs(grant("nobody", "tickets", "all", "view"), grant("crm_sales_manager", "tickets", "all", "view")), "ACCESS_ROLE_NOT_FOUND") + if len(users.asked) != 1 || !slices.Equal(users.asked[0], []string{"r-mgr"}) { + t.Fatalf("PrivilegedHolders asked %v; want [r-mgr]", users.asked) + } +} + func TestProposeAccess_RoleByLabelAndTablesNotYetPublished(t *testing.T) { // The builder says the label; the table was born after the last publish (still hidden). e := accessExecutor(fakeCutoff{at: &accCutoff}) diff --git a/nexus-platform/internal/ai/tools_explain_access_test.go b/nexus-platform/internal/ai/tools_explain_access_test.go index 0b8d5fd..8ab752e 100644 --- a/nexus-platform/internal/ai/tools_explain_access_test.go +++ b/nexus-platform/internal/ai/tools_explain_access_test.go @@ -8,6 +8,7 @@ package ai import ( "context" "encoding/json" + "slices" "strings" "testing" @@ -18,11 +19,21 @@ import ( type fakeAccessUsers struct { byKey map[string]*auth.User // key: tenantID+"/"+email or +id - byTenant map[string][]auth.User // ListUsers (propose_access) + byTenant map[string][]auth.User // PrivilegedHolders (propose_access) + asked [][]string // the roleIDs of each PrivilegedHolders call } -func (f *fakeAccessUsers) ListUsers(_ context.Context, tenantID string) ([]auth.User, error) { - return f.byTenant[tenantID], nil +// PrivilegedHolders filters as the SQL does (tenant, role in roleIDs, admin or operator) and records +// which roles were asked about. +func (f *fakeAccessUsers) PrivilegedHolders(_ context.Context, tenantID string, roleIDs []string) ([]auth.User, error) { + f.asked = append(f.asked, roleIDs) + var out []auth.User + for _, u := range f.byTenant[tenantID] { + if u.RoleID != nil && slices.Contains(roleIDs, *u.RoleID) && (u.IsAdmin || u.IsPlatformOperator) { + out = append(out, u) + } + } + return out, nil } func (f *fakeAccessUsers) GetUserByEmail(_ context.Context, tenantID, email string) (*auth.User, error) { diff --git a/nexus-platform/internal/audit/audit.go b/nexus-platform/internal/audit/audit.go index f4c8fbd..2783be3 100644 --- a/nexus-platform/internal/audit/audit.go +++ b/nexus-platform/internal/audit/audit.go @@ -170,7 +170,7 @@ const ( ) // Event is the payload a service emits after a mutation commits. RecordID is empty for -// admin-meta mutations (entity/field/role) that have no obj_* record. Diff is the +// admin-meta mutations (entity/field) that have no obj_* record; a role's rows carry the role id. Diff is the // {before,after} of only the fields that changed; create populates only after, delete only // before. At is the originating event time (the dispatcher stamps the row clock instead, but // At is carried for context/debug). All maps must be JSON-serializable. diff --git a/nexus-platform/internal/auth/user_privileged_holders_integration_test.go b/nexus-platform/internal/auth/user_privileged_holders_integration_test.go new file mode 100644 index 0000000..346a1b3 --- /dev/null +++ b/nexus-platform/internal/auth/user_privileged_holders_integration_test.go @@ -0,0 +1,65 @@ +//go:build integration + +// UserRepository.PrivilegedHolders against a real MySQL (issue #23): propose_access asks only for the +// admins and platform operators holding the roles it names, never every user of the tenant. +// +// bash scripts/run-integration.sh -run 'TestPrivilegedHolders_' ./internal/auth/ +package auth + +import ( + "context" + "slices" + "testing" + + "github.com/google/uuid" +) + +func TestPrivilegedHolders_OnlyAdminsAndOperatorsOfTheNamedRolesInTheTenant(t *testing.T) { + ctx := context.Background() + f := manageSetup(t) + role := func(tenant, name string) string { + t.Helper() + id := uuid.NewString() + if err := f.db.Exec(`INSERT INTO acl_roles (id, tenant_id, name, label) VALUES (?, ?, ?, ?)`, id, tenant, name, name).Error; err != nil { + t.Fatalf("seed role %s: %v", name, err) + } + return id + } + holder := func(tenant, roleID, label string, admin, operator bool) string { + t.Helper() + id := uuid.NewString() + f.seed(t, tenant, id, label, "active", admin, false, operator) + if err := f.db.Exec(`UPDATE users SET role_id = ? WHERE id = ?`, roleID, id).Error; err != nil { + t.Fatalf("give %s the role: %v", label, err) + } + return id + } + asked, other, unnamed := role(f.tenant, "ph_asked"), role(f.tenant, "ph_other"), role(f.tenant, "ph_unnamed") + admin := holder(f.tenant, asked, "admin", true, false) + operator := holder(f.tenant, other, "operator", false, true) + holder(f.tenant, asked, "staff", false, false) // holds a named role, but is neither + holder(f.tenant, unnamed, "admin2", true, false) // an admin of a role nobody asked about + holder(f.other, asked, "foreign", true, false) // another tenant's admin carrying this role id + gone := holder(f.tenant, asked, "gone", true, false) // soft-deleted + if err := f.db.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone).Error; err != nil { + t.Fatal(err) + } + + got, err := f.repo.PrivilegedHolders(ctx, f.tenant, []string{asked, other}) + if err != nil { + t.Fatalf("PrivilegedHolders: %v", err) + } + ids := make([]string, len(got)) + for i, u := range got { + ids[i] = u.ID + } + want := []string{admin, operator} + slices.Sort(ids) + slices.Sort(want) + if !slices.Equal(ids, want) { + t.Fatalf("holders = %v; want only the admin and the operator of the two named roles in this tenant %v", ids, want) + } + if none, err := f.repo.PrivilegedHolders(ctx, f.tenant, nil); err != nil || none != nil { + t.Fatalf("no roles = %v, %v; want nil without a query", none, err) + } +} diff --git a/nexus-platform/internal/auth/user_repository_crud.go b/nexus-platform/internal/auth/user_repository_crud.go index 2672537..9f1b278 100644 --- a/nexus-platform/internal/auth/user_repository_crud.go +++ b/nexus-platform/internal/auth/user_repository_crud.go @@ -70,6 +70,24 @@ func (r *UserRepository) ListUsers(ctx context.Context, tenantID string) ([]User return users, nil } +// PrivilegedHolders returns the tenant's admins and platform operators who hold one of roleIDs: +// the only users propose_access asks about (issue #23), instead of every user of the tenant. +// Pinned to tenant_id; an empty roleIDs is (nil, nil) without a query. +func (r *UserRepository) PrivilegedHolders(ctx context.Context, tenantID string, roleIDs []string) ([]User, error) { + if len(roleIDs) == 0 { + return nil, nil + } + var users []User + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND role_id IN ? AND (is_admin = ? OR is_platform_operator = ?)", tenantID, roleIDs, true, true). + Order("created_at ASC, id ASC"). + Find(&users).Error + if err != nil { + return nil, fmt.Errorf("auth.UserRepository.PrivilegedHolders: %w", err) + } + return users, nil +} + // CreateUser inserts u (which must already carry a server-derived ID and TenantID). A // duplicate (tenant_id, email) is reported as ErrUserAlreadyExists; any other failure is // wrapped. The caller is responsible for hashing the password before this runs — the repo diff --git a/nexus-platform/internal/handlers/mcp_integration_test.go b/nexus-platform/internal/handlers/mcp_integration_test.go index 969dbb1..cc7e3c0 100644 --- a/nexus-platform/internal/handlers/mcp_integration_test.go +++ b/nexus-platform/internal/handlers/mcp_integration_test.go @@ -15,6 +15,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "reflect" "strings" "sync" "testing" @@ -820,3 +821,82 @@ func TestMCP_SettledProposalsAreNotReplayed(t *testing.T) { mustPropose(t, "propose_field", map[string]any{"entity": "st_visits", "name": "doctor", "label": "Doctor", "fieldType": "user"}) // doctor_id is free }) } + +// Issue #23: an outside agent answers "who can edit contacts?" whole. nexus_list_roles {grants: true} +// lists this workspace's roles with their grants (the role reader main.go wires). A token of tenant A +// never sees tenant B's roles or grants (nor B's token A's), and as a read it writes nothing: no +// role or grant changes, and the token's thread keeps only its opening turn. +func TestMCP_ListRolesWithGrants(t *testing.T) { + gdb, sx := a4SetupMigratedDB(t) + ctx := context.Background() + const tenantA, tenantB = "ten-mcp-grants", "ten-mcp-grants-b" + builderA := mcpBuilder(t, gdb, tenantA, "mcp-grants") + builderB := mcpBuilder(t, gdb, tenantB, "mcp-grants-b") + roleRepo := auth.NewRoleRepository(gdb) + roles := services.NewRoleService(roleRepo) + if _, err := roles.CreateRole(ctx, tenantA, services.CreateRoleInput{Name: "it_contacts_editor", Label: "Contacts editor", Actions: []services.RoleActionInput{ + {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}, {EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}}}); err != nil { + t.Fatalf("role A: %v", err) + } + // B's role grants on a table of the same name: a leak would show up as a role or as a grant. + if _, err := roles.CreateRole(ctx, tenantB, services.CreateRoleInput{Name: "it_b_contacts_admin", Label: "B", Actions: []services.RoleActionInput{ + {EntityName: "it_contacts", Action: "delete", AccessLevel: "all"}, {EntityName: "*", Action: "edit", AccessLevel: "all"}}}); err != nil { + t.Fatalf("role B: %v", err) + } + store := ai.NewSessionStore(sx) + mcpSvc := services.NewMCPTokenService(auth.NewMCPTokenRepository(gdb), store, auth.NewUserRepository(gdb)) + agent := ai.NewAIBuilderAgent(config.AIConfig{}, nil, ai.ReaderWithAccessProbes(metadata.NewRepository(gdb), &ai.AccessProbes{Roles: roleRepo}), nil, nil, zap.NewNop()) + ts := httptest.NewServer(mcpserver.New(mcpSvc, agent, store, nil, zap.NewNop())) + defer ts.Close() + + type role struct { + Name string `json:"name"` + Grants []services.RoleActionView `json:"grants"` + } + count := func(q string, args ...any) int { + t.Helper() + var n int + if err := sx.Get(&n, q, args...); err != nil { + t.Fatalf("%s: %v", q, err) + } + return n + } + grantsBefore := count("SELECT COUNT(*) FROM acl_role_actions") + rolesBefore := count("SELECT COUNT(*) FROM acl_roles") + listAs := func(tenant, builderID string) []role { + t.Helper() + tok, secret, err := mcpSvc.Issue(ctx, auth.Subject{UserID: builderID, TenantID: tenant, IsAdmin: true}, nil) + if err != nil { + t.Fatalf("issue %s: %v", tenant, err) + } + res, err := mcpConnect(t, ts.URL, secret).CallTool(ctx, &mcp.CallToolParams{Name: "nexus_list_roles", Arguments: map[string]any{"grants": true}}) + if err != nil || res.IsError { + t.Fatalf("list_roles grants as %s: %v %s", tenant, err, mcpText(res)) + } + var out struct { + Result struct { + Roles []role `json:"roles"` + } `json:"result"` + } + if err := json.Unmarshal([]byte(mcpText(res)), &out); err != nil { + t.Fatalf("decode %s: %v", mcpText(res), err) + } + if n := count("SELECT COUNT(*) FROM sys_ai_messages WHERE session_id = ? AND tenant_id = ?", tok.SessionID, tenant); n != 2 { + t.Fatalf("%s thread rows = %d; want only the 2 of the key's opening turn", tenant, n) + } + return out.Result.Roles + } + + gotA := listAs(tenantA, builderA) + wantA := []role{{Name: "it_contacts_editor", Grants: []services.RoleActionView{{EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}, {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}}}} + if !reflect.DeepEqual(gotA, wantA) { + t.Fatalf("tenant A's token sees %+v; want only its own role and grants %+v", gotA, wantA) + } + gotB := listAs(tenantB, builderB) + if len(gotB) != 1 || gotB[0].Name != "it_b_contacts_admin" || len(gotB[0].Grants) != 2 { + t.Fatalf("tenant B's token sees %+v; want only its own role with its 2 grants", gotB) + } + if g, r := count("SELECT COUNT(*) FROM acl_role_actions"), count("SELECT COUNT(*) FROM acl_roles"); g != grantsBefore || r != rolesBefore { + t.Fatalf("after two reads: %d grants, %d roles; want %d and %d (a read writes nothing)", g, r, grantsBefore, rolesBefore) + } +} diff --git a/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go b/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go index d805cb2..b6d6609 100644 --- a/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go +++ b/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go @@ -369,7 +369,8 @@ func TestRM19_RecordMutations_WriteOneAuditRowEach(t *testing.T) { // TestRM19_AdminMetaMutations_WriteAuditRows proves entity-create, field-add and role-create each // write one admin-meta audit row (__entity__/__field__/__role__) attributed to the caller, with -// NULL record_id (admin-meta mutations have no obj_* record). +// NULL record_id (admin-meta mutations have no obj_* record) — except the role's, which carries the +// role id (issue #23), and a role update, whose diff names the role even when only grants changed. func TestRM19_AdminMetaMutations_WriteAuditRows(t *testing.T) { gdb, sx := a4SetupMigratedDB(t) auditRequireSchemaV14(t, sx) @@ -396,12 +397,26 @@ func TestRM19_AdminMetaMutations_WriteAuditRows(t *testing.T) { } // Role create → __role__ row. + var role struct { + Data struct { + Role struct { + ID string `json:"id"` + } `json:"role"` + } `json:"data"` + } if w := doAuthed(t, rt.engine, "POST", "/api/v1/admin/roles", token, map[string]any{ "name": "rm19_viewer", "label": "RM19 Viewer", "actions": []map[string]any{{"entityName": entity, "action": "view", "accessLevel": "all"}}, - }, nil); w.Code != http.StatusCreated { + }, nil); w.Code != http.StatusCreated || json.Unmarshal(w.Body.Bytes(), &role) != nil || role.Data.Role.ID == "" { t.Fatalf("create role: HTTP %d; body=%s", w.Code, w.Body.String()) } + // Grants-only update, as the AI's access card applies it → a __role__ update row naming the role. + if w := doAuthed(t, rt.engine, "PUT", "/api/v1/admin/roles/"+role.Data.Role.ID, token, map[string]any{ + "name": "rm19_viewer", "label": "RM19 Viewer", + "actions": []map[string]any{{"entityName": entity, "action": "view", "accessLevel": "all"}, {"entityName": entity, "action": "edit", "accessLevel": "owner"}}, + }, nil); w.Code != http.StatusOK { + t.Fatalf("update role: HTTP %d; body=%s", w.Code, w.Body.String()) + } rt.drain(t) @@ -427,10 +442,27 @@ func TestRM19_AdminMetaMutations_WriteAuditRows(t *testing.T) { if r.TenantID != tenantID { t.Errorf("%s row tenant=%q; want %q", key, r.TenantID, tenantID) } + if key == audit.RoleMeta { + if r.RecordID == nil || *r.RecordID != role.Data.Role.ID { + t.Errorf("%s row record_id=%v; want the role id %q", key, r.RecordID, role.Data.Role.ID) + } + continue + } if r.RecordID != nil { t.Errorf("%s row record_id=%v; want NULL (admin-meta)", key, *r.RecordID) } } + var upd *auditLogRow + for i := range rows { + if rows[i].EntityName == audit.RoleMeta && rows[i].Action == audit.ActionUpdate { + upd = &rows[i] + } + } + var diff audit.Diff + if upd == nil || upd.RecordID == nil || *upd.RecordID != role.Data.Role.ID || json.Unmarshal(upd.Diff, &diff) != nil || + diff.Before["name"] != "rm19_viewer" || diff.After["name"] != "rm19_viewer" { + t.Fatalf("role update row = %+v; want record_id %q and the role's name on both sides of its diff", upd, role.Data.Role.ID) + } } // TestRM19_TeamMetaMutations_WriteAuditRows closes the __team__ zero-emit gap diff --git a/nexus-platform/internal/mcpserver/mcpserver_test.go b/nexus-platform/internal/mcpserver/mcpserver_test.go index 81bb413..1bc1883 100644 --- a/nexus-platform/internal/mcpserver/mcpserver_test.go +++ b/nexus-platform/internal/mcpserver/mcpserver_test.go @@ -69,7 +69,7 @@ func TestTools_AreTheBuilderAgentsReadAndProposeToolsOnly(t *testing.T) { if len(got) != want { t.Errorf("exposed %d tools, want the %d of the builder agent", len(got), want) } - for _, n := range []string{"list_entities", "list_fields", "list_relationships", "snapshot_model", "explain_access", + for _, n := range []string{"list_entities", "list_fields", "list_relationships", "list_roles", "snapshot_model", "explain_access", "propose_entity", "propose_field", "propose_relationship", "propose_layout"} { if _, ok := got[toolPrefix+n]; !ok { t.Errorf("core tool %s%s missing", toolPrefix, n) diff --git a/nexus-platform/internal/services/audit_emit.go b/nexus-platform/internal/services/audit_emit.go index d5760c2..25a87af 100644 --- a/nexus-platform/internal/services/audit_emit.go +++ b/nexus-platform/internal/services/audit_emit.go @@ -29,6 +29,12 @@ func emitMetaAudit(ctx context.Context, a audit.Auditor, tenantID, metaEntity, a // GET /audit-log?entityName=__user__&recordId= returns the whole account history alongside // the W7 reset-link row (auth_password_reset.go), which already uses RecordID=userId. func emitMetaAuditFor(ctx context.Context, a audit.Auditor, tenantID, metaEntity, recordID, action string, before, after any) { + emitMetaDiff(ctx, a, tenantID, metaEntity, recordID, action, audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after))) +} + +// emitMetaDiff is emitMetaAuditFor with a diff the caller has already built (a role update adds the +// role's name to both sides, role_service.go). +func emitMetaDiff(ctx context.Context, a audit.Auditor, tenantID, metaEntity, recordID, action string, diff *audit.Diff) { if a == nil { // a service built by struct literal in a test has no auditor; the trail is best-effort anyway return } @@ -38,7 +44,7 @@ func emitMetaAuditFor(ctx context.Context, a audit.Auditor, tenantID, metaEntity EntityName: metaEntity, RecordID: recordID, Action: action, - Diff: audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after)), + Diff: diff, At: time.Now().UTC(), }) } diff --git a/nexus-platform/internal/services/role_service.go b/nexus-platform/internal/services/role_service.go index 9ff44bc..91f8a6d 100644 --- a/nexus-platform/internal/services/role_service.go +++ b/nexus-platform/internal/services/role_service.go @@ -264,8 +264,8 @@ func (s *RoleService) CreateRole(ctx context.Context, tenantID string, in Create v := roleToView(role, actions) // Invalidate the new role's cached grants AFTER commit (defensive — nothing cached yet) (O3). s.aclCache.Invalidate(tenantID, role.ID) - // RM-19: audit the committed role create (after-only diff). Async + fail-open. - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionCreate, nil, v) + // RM-19: audit the committed role create (after-only diff) on the role's own row. Async + fail-open. + emitMetaAuditFor(ctx, s.auditor, tenantID, audit.RoleMeta, role.ID, audit.ActionCreate, nil, v) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: role.ID, Label: roleLabel(v), Op: "create", After: v}) return &v, nil } @@ -349,9 +349,8 @@ func (s *RoleService) UpdateRole(ctx context.Context, tenantID, id string, in Up v := roleToView(role, current) // Invalidate the role's cached grants AFTER commit so changed/revoked grants take effect now (O3). s.aclCache.Invalidate(tenantID, id) - // RM-19: audit the committed role update. We record the after-view; the diff highlights the - // fields present (name/label/actions). Async + fail-open. - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionUpdate, beforeView, v) + // RM-19: audit the committed role update on the role's own row. Async + fail-open. + emitMetaDiff(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionUpdate, roleUpdateDiff(beforeView, v)) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabel(v), Op: "update", Before: beforeView, After: v}) return &v, nil } @@ -385,7 +384,7 @@ func (s *RoleService) Recreate(ctx context.Context, tenantID, id string, before } s.aclCache.Invalidate(tenantID, id) v := roleToView(role, actions) - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionCreate, nil, v) + emitMetaAuditFor(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionCreate, nil, v) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabel(v), Op: "create", After: v, Meta: map[string]any{"reassignedUserIds": userIDs, "reassigned": n}}) return int(n), nil @@ -450,8 +449,8 @@ func (s *RoleService) DeleteRole(ctx context.Context, tenantID, id string) error } // Invalidate the deleted role's cached grants AFTER commit so it can no longer authorize (O3). s.aclCache.Invalidate(tenantID, id) - // RM-19: audit the committed role delete (before-only diff). Async + fail-open. - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionDelete, beforeView, nil) + // RM-19: audit the committed role delete (before-only diff) on the role's own row. Async + fail-open. + emitMetaAuditFor(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionDelete, beforeView, nil) rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabelAny(beforeView), Op: "delete", Before: beforeView, Meta: meta}) return nil } @@ -538,6 +537,29 @@ func roleToView(r *auth.Role, actions []auth.RoleAction) RoleView { return v } +// roleUpdateDiff is a role update's audit diff with the role's name on both sides (issue #23): an +// update diff keeps only the changed keys, so a grants-only change, or a save that changes nothing, +// would otherwise leave a row that names no role. before is the RoleView read before the update (nil +// when there was none to read: the row then names the role by its name after). +func roleUpdateDiff(before any, after RoleView) *audit.Diff { + priorName := after.Name + if b, ok := before.(RoleView); ok { + priorName = b.Name + } + d := audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after)) + if d == nil { + d = &audit.Diff{} + } + if d.Before == nil { + d.Before = map[string]any{} + } + if d.After == nil { + d.After = map[string]any{} + } + d.Before["name"], d.After["name"] = priorName, after.Name + return d +} + func roleLabel(v RoleView) string { if v.Label != "" { return v.Label diff --git a/nexus-platform/internal/services/role_service_audit_test.go b/nexus-platform/internal/services/role_service_audit_test.go new file mode 100644 index 0000000..94bd820 --- /dev/null +++ b/nexus-platform/internal/services/role_service_audit_test.go @@ -0,0 +1,58 @@ +package services + +// Issue #23: a role's audit rows name the role. An update diff keeps only the changed keys, so a +// grants-only change (the AI's access card) used to leave a __role__ row with record_id NULL and no +// name: the audit log alone could not say which role changed. + +import ( + "context" + "testing" + + "nexus/platform/internal/audit" +) + +func TestRole_AuditRowsNameTheRole(t *testing.T) { + ctx := context.Background() + svc, _ := newRoleSvc() + cap := &captureAuditor{} + svc.WithAuditor(cap) + created, err := svc.CreateRole(ctx, "t1", CreateRoleInput{Name: "sales", Label: "Sales", Actions: []RoleActionInput{{EntityName: "contacts", Action: "view"}}}) + if err != nil { + t.Fatal(err) + } + // Grants only, as the access card's apply writes it: the name is resent unchanged. + name, label := "sales", "Sales" + if _, err := svc.UpdateRole(ctx, "t1", created.ID, UpdateRoleInput{Name: &name, Label: &label, + Actions: []RoleActionInput{{EntityName: "contacts", Action: "view"}, {EntityName: "tickets", Action: "view"}}}); err != nil { + t.Fatal(err) + } + // Nothing changes at all: the row still says which role was saved. + if _, err := svc.UpdateRole(ctx, "t1", created.ID, UpdateRoleInput{Label: &label}); err != nil { + t.Fatal(err) + } + renamed := "sales_team" + if _, err := svc.UpdateRole(ctx, "t1", created.ID, UpdateRoleInput{Name: &renamed}); err != nil { + t.Fatal(err) + } + if err := svc.DeleteRole(ctx, "t1", created.ID); err != nil { + t.Fatal(err) + } + + if len(cap.events) != 5 { + t.Fatalf("events = %d; want create, three updates, delete", len(cap.events)) + } + for i, e := range cap.events { + if e.EntityName != audit.RoleMeta || e.RecordID != created.ID { + t.Errorf("event %d (%s) = %s/%q; want __role__ with record_id = the role's id %q", i, e.Action, e.EntityName, e.RecordID, created.ID) + } + } + for i, want := range [][2]string{{"sales", "sales"}, {"sales", "sales"}, {"sales", "sales_team"}} { + d := cap.events[1+i].Diff + if d == nil || d.Before["name"] != want[0] || d.After["name"] != want[1] { + t.Errorf("update %d diff = %+v; want name %q -> %q", i+1, d, want[0], want[1]) + } + } + if d := cap.events[1].Diff; d.After["actions"] == nil { + t.Errorf("grants-only update diff = %+v; want the changed actions kept", d) + } +} diff --git a/nexus-web/components/studio/AccessMatrix.test.tsx b/nexus-web/components/studio/AccessMatrix.test.tsx index d3bda0f..de6dff8 100644 --- a/nexus-web/components/studio/AccessMatrix.test.tsx +++ b/nexus-web/components/studio/AccessMatrix.test.tsx @@ -226,12 +226,13 @@ describe("delivered project: 'Áp ngay cho người dùng thật' (lát f2-direc describe("assistant preview (an access card)", () => { const card = (before: RoleGrant[], after: RoleGrant[], labels: Record) => mkChange("role", "update", { docKey: "r3", target: { name: "r3", entity: Object.keys(labels)[0] }, before: { grants: before, labels }, after: { grants: after, labels } }); - function Page({ roles, tables }: { roles: RoleDetail[]; tables: { name: string; label: string }[] }) { - const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, tables); - return ; + // `tables` is what the page draws (?app= / ?bang= may leave some out), `built` every table of the project. + function Page({ roles, tables, built = tables }: { roles: RoleDetail[]; tables: { name: string; label: string }[]; built?: { name: string; label: string }[] }) { + const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, built, tables); + return ; } - const renderWith = (c: ReturnType | null) => - render(); + const renderWith = (c: ReturnType | null, tables = TABLES) => + render(); const onVisit = card([g("invoice", "create")], [g("invoice", "create"), g("visit", "view"), g("visit", "create"), g("visit", "edit", "owner")], { visit: "Lịch hẹn" }); it("tints the card's cell, says the level it leads to and the one it replaces; other cells stay plain", async () => { @@ -271,6 +272,18 @@ describe("assistant preview (an access card)", () => { expect(screen.queryByRole("combobox", { name: /Phiếu hỗ trợ/ })).toBeNull(); }); + // issue #23: the page filtered to an app that leaves the card's (built) table out still draws its ghost cell, on the + // table's real, editable column. + it("a built table outside the ?app= filter gets its column, so the ghost cell is drawn", async () => { + renderWith(onVisit, [TABLES[0]]); + const td = (await screen.findByText("Xem và sửa · Đề xuất")).closest("td")!; + expect(td.className).toContain("nx-proposed"); + expect(within(td).getByRole("combobox", { name: name("Kế toán", "Lịch hẹn", "Không thấy") })).toBeInTheDocument(); + const head = screen.getByRole("columnheader", { name: "Lịch hẹn" }); + expect(head.className).not.toContain("nx-proposed"); + expect(screen.getAllByRole("columnheader")).toHaveLength(3); + }); + it("Bỏ (clear) removes the ghost and leaves the real grants alone", async () => { renderWith(onVisit); await screen.findByText("Xem và sửa · Đề xuất"); diff --git a/nexus-web/components/studio/AccessMatrix.tsx b/nexus-web/components/studio/AccessMatrix.tsx index bf02925..c8ee61d 100644 --- a/nexus-web/components/studio/AccessMatrix.tsx +++ b/nexus-web/components/studio/AccessMatrix.tsx @@ -41,16 +41,21 @@ const tierText = (v: unknown, table: string): string | null => { const accessTablesOf = (c: ProposedChange | null): string[] => Object.keys(side(c?.after).labels ?? {}); /** - * What the access card being previewed draws on the page: its role's cells (`proposed`) and, as read-only columns, the - * tables it names that are not built yet (the table card is still to be applied). + * What the access card being previewed draws on the page: its role's cells (`proposed`) and the columns of the tables it + * names that the page does not draw (`extra`, `shown` = the drawn tables): a table not built yet is a read-only column + * (the table card is still to be applied); a built one that `?app=` / `?bang=` left out gets its own column, or its + * ghost cell would have nowhere to go (issue #23). */ -export function accessGhost(change: ProposedChange | null, roles: readonly RoleDetail[], built: readonly { name: string }[]) { +export function accessGhost(change: ProposedChange | null, roles: readonly RoleDetail[], built: readonly { name: string; label?: string }[], shown: readonly { name: string }[]) { const tables = accessTablesOf(change); const role = change ? roles.find((r) => r.id === change.docKey || r.name === change.target.name) : undefined; const labels = side(change?.after).labels ?? {}; return { proposed: role ? new Set(tables.map((n) => `${role.id}|${n}`)) : undefined, - pending: tables.filter((n) => !built.some((e) => e.name === n)).map((n) => ({ name: n, label: labels[n] || n, pending: true })), + extra: tables.filter((n) => !shown.some((e) => e.name === n)).map((n) => { + const table = built.find((e) => e.name === n); + return table ? { name: n, label: table.label || n } : { name: n, label: labels[n] || n, pending: true }; + }), }; } function GhostNote({ change, table }: { change: ProposedChange; table: string }) { diff --git a/nexus-web/components/studio/ChangeList.test.tsx b/nexus-web/components/studio/ChangeList.test.tsx index 0102cd7..0a0ff6e 100644 --- a/nexus-web/components/studio/ChangeList.test.tsx +++ b/nexus-web/components/studio/ChangeList.test.tsx @@ -27,6 +27,16 @@ describe("ChangeList", () => { expect(rows[0].textContent).toContain("Luật gửi thư"); }); + // issue #23: a long line (a rule's condition, a grant, a path) wraps instead of being cut to one line. + it("a long line wraps, the mark stays on its first line", () => { + render(); + const row = screen.getByRole("listitem"); + const text = within(row).getByText(/người phụ trách/); + expect(text.className).not.toContain("slds-truncate"); + expect(text.className).toContain("slds-hyphenate"); + expect(row.className).toContain("slds-grid_vertical-align-start"); + }); + it("tone=proposed marks the list as an assistant proposal", () => { const { container } = render(); expect(container.querySelector("ul")?.className).toContain("nx-proposed"); diff --git a/nexus-web/components/studio/ChangeList.tsx b/nexus-web/components/studio/ChangeList.tsx index 7f81781..b490627 100644 --- a/nexus-web/components/studio/ChangeList.tsx +++ b/nexus-web/components/studio/ChangeList.tsx @@ -1,5 +1,6 @@ // ChangeList — "+ ~ − =" list of changes (specs/073 UI-ARCH 5.3). The mark is decoration (aria-hidden); the word beside it is -// for screen readers. Used by PublishReview and, with tone="proposed", by assistant proposals. +// for screen readers. Used by PublishReview and, with tone="proposed", by assistant proposals. A long line wraps (a rule's +// condition, a grant, a path): cut to one line it hid the part the builder had to read (issue #23). import clsx from "clsx"; import type { ReactNode } from "react"; import { t } from "@/lib/i18n"; @@ -19,10 +20,10 @@ export function ChangeList({ items, tone = "neutral", label }: { items: readonly return (
    {items.map((it, i) => ( -
  • +
  • {t(MARK[it.op].word)} - {it.text} + {it.text}
  • ))}
diff --git a/nexus-web/components/studio/build/AccessPage.test.tsx b/nexus-web/components/studio/build/AccessPage.test.tsx index f905021..5e1f38e 100644 --- a/nexus-web/components/studio/build/AccessPage.test.tsx +++ b/nexus-web/components/studio/build/AccessPage.test.tsx @@ -47,6 +47,7 @@ vi.mock("@/lib/admin", async (orig) => ({ })); import { AccessPage } from "./AccessPage"; +import { mkChange, WithPreview } from "@/test/previewProbe"; const ROLES = [ role("r1", "Lễ tân", [{ entityName: "invoice", action: "view", accessLevel: "all" }]), @@ -152,6 +153,24 @@ describe("app filter and related column", () => { expect(screen.getByRole("combobox", { name: "Xem theo app" })).toHaveValue("clinic"); }); + // issue #23: the assistant's access card names a built table the ?app= filter leaves out; the page still draws that + // table's column, so the card's ghost cell is there to see. + it("?app= that leaves out the card's table still draws its column and the ghost cell", async () => { + const after = { grants: [{ entityName: "invoice", action: "view", accessLevel: "all" }], labels: { invoice: "Hoá đơn" } }; + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + + + , + ); + const td = (await screen.findByText("Chỉ xem · Đề xuất")).closest("td")!; + expect(td.className).toContain("nx-proposed"); + expect(within(td).getByRole("combobox", { name: "Kế toán trên Hoá đơn: Không thấy" })).toBeInTheDocument(); + expect(screen.getByRole("combobox", { name: /Lễ tân trên Lịch hẹn/ })).toBeInTheDocument(); + }); + it("?bang= narrows to that table and offers the way back to all", async () => { renderPage({ bang: "invoice" }); await screen.findByRole("combobox", { name: /Lễ tân trên Hoá đơn/ }); diff --git a/nexus-web/components/studio/build/AccessPage.tsx b/nexus-web/components/studio/build/AccessPage.tsx index 9bf09c3..e444923 100644 --- a/nexus-web/components/studio/build/AccessPage.tsx +++ b/nexus-web/components/studio/build/AccessPage.tsx @@ -52,8 +52,8 @@ export function AccessPage({ slug, app: appParam, bang }: { slug: string; app?: const { visible, hidden } = splitByScope(entities, scope.entityNames, (e) => e.name); const tables = (bang ? visible.filter((e) => e.name === bang) : visible).map((e) => ({ name: e.name, label: e.label || e.name })); - // The assistant's access card being previewed ("Xem trước"): its role's cells, and the tables it names not built yet. - const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, entities); + // The assistant's access card being previewed ("Xem trước"): its role's cells, and the tables it names the page does not draw. + const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, entities, tables); // ── "+ Vai mới" strip ── const [open, setOpen] = useState(false); @@ -139,7 +139,7 @@ export function AccessPage({ slug, app: appParam, bang }: { slug: string; app?: body = ( studioHref(slug, "dung/nguoi-dung-quyen/vai/:id", { id })} diff --git a/nexus-web/lib/aiProposalView.ts b/nexus-web/lib/aiProposalView.ts index eb1c526..66dcb6b 100644 --- a/nexus-web/lib/aiProposalView.ts +++ b/nexus-web/lib/aiProposalView.ts @@ -218,8 +218,9 @@ export function proposalView(item: AiDraftItem, ctx: Ctx = {}): ProposalView | n } const ac = item.kind === "access" ? getAccessDraft(item) : undefined; if (ac) { - // The title is the whole sentence, so it wraps instead of being cut: "Nhân viên kinh doanh được xem tất cả · tạo · sửa - // của mình trên Phiếu hỗ trợ" (one clause per table); the list has one short "+" line per grant. + // The title is the whole sentence, which the in-place question also reads ("Quyền này áp ngay cho người dùng thật: …"): + // "Nhân viên kinh doanh được xem tất cả · tạo · sửa của mình trên Phiếu hỗ trợ" (one clause per table); the list has + // one "+" line per grant. const role = ac.roleLabel || ac.role; const label = (n: string) => ac.labels?.[n] || n; const tables = [...new Set(ac.grants.map((g) => g.entityName))];